×
Q: Handling errors while using Async/Await (JavaScript ES8)


Q: Handling errors while using Async/Await (JavaScript ES8)

October 20, 2019

This article aims at providing an insight into handling errors while using async-await.

In the below example, a  function TestPromise will return a promise.The promise will give an error and get rejected if the value of the variable budget is less than 20000. The promise will always get rejected as we initialize the value of  budget to be 10000. A function calltestAPromise calls the function TestPromise.

 

As shown above function calltestAPromise will call TestPromise and handle the promise it returns with .then  and .catch, an error will get caught in the .catch which will handle the rejected case. The above promise will get rejected with an error.

 

Now change the function calltestAPromise to be an async function which will await for the promise to get resolved or rejected.

Now, the promise returned by TestPromise will get rejected with an error. The error won’t be handled and the promise rejection will be left unhandled. If the promise gets rejected, the code will never reach the console.log.

Handling the error on a promise can be achieved by wrapping the block of code inside a try-catch. The rejected error on promise will be caught by the catch.

The catch of try/catch will catch the error of the promise rejection and the error will be handled in the above way. The error can be sent to the caller using res.send while building an API.

 

By creating a try/catch block, the async function can handle an error of the rejected promise.

See more descriptions about async/await here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

 

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *