Handling errors and exceptions using Async Await

Viewed 28

I am writing some promise heavy scripts at the moment and I am trying to identify the best way to catch and manage responses and errors. Alot of my code requires previous code to have been resolved and confirmed. As a response failure could be an object saying why it failed I need to do a comparison to see if X is in the actual response and as such I am asking for the best way to move forward after a promise is resolved. I have three of my written scenarios below

/* 
    First potential method?
    Smart supporting function??
*/
// Error catching in the supporting function??
async function runfakeFunction() {
    try {
    var output = await fakeFunction({}).promise()
    return await output
    } catch(err) {
        console.error(err)
    }
}
// Call the above function and store it?
var response = await runfakeFunction()

// Ensure the output I returned is as expected?
if(response !== undefined){
    console.log('success')
} else {
    console.log('errored')
}

/* 
    Second potential method?
    Dumb supporting function??
    Follow up question is would I just nest my supporting functions in the .then() block or would I store the response and use a seperate function??
*/
async function runfakeFunction() {
    return await fakeFunction({}).promise() // for this dumb function .promise() is required
}

runfakeFunction().then((response) => {
    // run next dependant code here?
}).catch((err) => {
    // run failure code here?
})

/* 
    Third potential method?
    Try and Catch block around the base SDK function
*/
try{
    var testing = await fakeFunction({}).promise() // for this dumb function .promise() is required
} catch (e) {

}
// Ensure the output I returned is as expected?
if(testing !== undefined){
    console.log('success')
} else {
    console.log('errored')
}
0 Answers
Related