Friday, 10 August 2018

async/await in node.js: error handling

So, let's have a quick look at async await error handling!

Like last time we are wrapping our code in a self-executing function so we can use the async keywords.

To handle errors in async functions we use a try-catch block like we normally would in synchronous code. You can see from the example that a rejected promise comes out of our catch block.

As we know from previous posts a promise will be rejected if reject() is called or an error is thrown inside of the promise.

Also if you throw an error in an async function this results in a rejected promise. So you can see now how it all fits together, any promise rejections or errors thrown result in the catch block being used.

Just worthy to note that non-awaited rejected promises will not trigger the catch block but will put up an unhandled promise rejection error.

No comments:

Post a Comment