Friday, 10 August 2018

async/await in node.js: error handling

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

(async function() {
try {
await Promise.reject('test')
} catch (err) {
console.error('bwoke', err)
}
})()
view raw errors.js hosted with ❤ by GitHub
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.

function throwPromise() {
return new Promise((resolve, reject) => {
throw new Error('An error happened inside the promise, but not rejected')
})
}
throwPromise()
.then(() => {
console.log("This won't get executed")
})
.catch(err => {
console.log('This handles the thrown error')
})
view raw errors.js hosted with ❤ by GitHub
As we know from previous posts a promise will be rejected if reject() is called or an error is thrown inside of the promise.

async function rejected() {
throw 'error'
}
(async function() {
try {
await rejected()
} catch (err) {
console.error('bwoke', err)
}
})()
view raw errors.js hosted with ❤ by GitHub
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.

(async function() {
try {
Promise.reject('test')
await Promise.reject('test 2')
} catch (err) {
console.error('bwoke', err)
}
})()
view raw errors.js hosted with ❤ by GitHub
Just worthy to note that non-awaited rejected promises will not trigger the catch block but will put up an unhandled promise rejection error.

3 comments:

  1. After logging in on the site, find a way to|you possibly can} view the promotions obtainable for the present week. Spin Casino has a month-to-month calendar of promotional offers masking match bonuses, bet365 free spins, and other rewards. You’ll additionally get access to the Spin Casino Bonus Wheel, where find a way to|you possibly can} win further spins, bonus credits, and loyalty factors every four hours. As if over 500 video games weren't sufficient, Spin Casino additionally has a Spin Vegas section.

    ReplyDelete