Error Handling with .catch()

Error Handling with .catch()

  • Promises chains are a great place to handle errors

  • The .catch() method provides us with an easy way to catch any errors that occur in a Promise chain


Example

const myPromise = () => {
  return new Promise((resolve, reject) => {
    // return 1 after the promise is resolved
    setTimeout(() => resolve(1), 2000)
  })
}

myPromise().then((result) => {
  console.log(result)
  return result + 1
}).then((result) => {
  console.log(result)
  return result + 1
}).then((result) => {
  throw new Error('FAILED HERE') // <- simulate an error in the promise chain
  console.log(result)
  return result + 1
}).catch((e) => {
  // catch error that occurs anywhere
  // the promise chain
  console.log('an error occurred')
  console.log(e)
})

JS Bin on jsbin.com


Example #2: Handling errors with our Superhero fetcher

  • Let’s use .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}`)
  })
}

function fetchHeroes() {
  /*
    use .catch() to catch any errors that occur
    during our asynchronous operation
 */

 getSuperheroes()
   .then((fetchedHeroes) => {
     printHeroes(fetchedHeroes)
   }).catch((e) => {
    console.log(e)
   })
}

console.log("Calling fetchHeroes()")
fetchHeroes()
console.log("end of the code")

JS Bin on jsbin.com