When a promise called using async / await, either it is success / resolve or reject. When async / await used without Error Handling, it breaks code execution when promise rejects. To do not break executiona and keep code running even when there are promise reject, we can use Error Handling with Asysc / Await. The same can be done with normal javascript try catch statements.
Consider a process
function which returns promise. And arguments passed to process
function decides if promise resolve or reject, how many seconds wait to resolve or reject as well as what data will it return when resolve.
function process(val, sec, rej = false) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (!rej) {
resolve(val);
} else {
reject('Error');
}
}, sec);
});
}
Now let’s test it with async / await without Handle any Error which will break execution and throw error if promise reject, as explained before.
(async () => {
console.log('running before error');
console.log(await process('2 sec request', 2000, true));
console.log('running after error');
})();
Here is the output of execution of code with async / await function but without Error Handling.

Error Handling with Async / Await function calling
Let’s change the code of the functions which calls promise with async / await function. And integrate Error Handling. Here, try is code block where code tested and if any error found. It stops execution at that point and starts catch block execution to handle error. If no error found, catch block will not be executed.
(async () => {
console.log('running before error');
try {
console.log(await process('2 sec request', 2000, true));
} catch (err) {
console.log(err);
}
console.log('running after error');
})();
Here is the output of execution of code with async / await function but with Error Handling.

Here you may have noticed that first log “running before error” is printed on both outputs. But second log “running after error” is only printed on output of code with Error Handling. You can also see that rejcted error is logged by catch method. So what happen is, when promise get rejected, it throws error. And also breaks code execution when Error Handling is not used. But b’cos of try catch (Error Handling) when promise get rejected, the catch code block executed and handles error and not break code execution.
If you like this, you may interested in one of my other blog about “Multiple async / await function calls parallel or sequential“
Leave A Comment