Error Handling with Async / Await
Error Handling with Async / Await
- With Async / Await we can use
try..catch
block to easily catch errors
Example
function yayOrNay() {
return new Promise((resolve, reject) => {
const val = Math.round(Math.random() * 1) // 0 or 1, at random
val ? resolve('Lucky!!') : reject('Nope 😠')
})
}
async function msg() {
// use try..catch to handle any potential errors
// when using "async / await"
try {
const msg = await yayOrNay();
console.log(msg)
} catch(err) {
console.log(err)
}
}
msg()
msg()
msg()
msg()
msg()
msg()
JS Bin on jsbin.com
- Notice how all of your “async-related” code lives inside the
try {}
portion of the try..catch
block
Example #2: Handling errors with our Superhero fetcher
- Let’s use
try..catch
to any errors that occur with our Superhero fetcher program
function getSuperheroes() {
return new Promise((resolve, reject) => {
setTimeout(() => {
// comment out to simulate reject()
/* resolve([
{ name: "Captain Marvel", team: "Avengers" },
{ name: "Batman", team: "Justice League"},
{ name: "Jean Grey", team: "X-Men"},
{ name: "Domino", team: "X-Force"}
]) */
// reject promise
reject("Oh no!!! An error occurred while fetching heroes.")
}, 3000)
});
}
function printHeroes(heroes) {
heroes.forEach((hero) => {
console.log(`name: ${hero.name}, team: ${hero.team}`)
})
}
async function fetchHeroes() {
/*
use `try..catch` to catch any errors that occur
during our asynchronous operation
*/
try {
const fetchedHeroes = await getSuperheroes()
printHeroes(fetchedHeroes)
} catch (e) {
console.log(e)
}
}
console.log("Calling fetchHeroes()")
fetchHeroes()
console.log("end of the code")
JS Bin on jsbin.com