Skip to content
Advertisement

Why would you try-catch around a promise? Does that catch the promise’s error?

I stumbled upon some code that looked off to me:

try {
  somePromise()
    .then(res => console.log(res));
} catch (err) {
  console.error(err);
}

If some somePromise() fails, would this not get caught, and the app would crash? Does this try-catch even do anything?

Should be this, correct?:

  somePromise()
    .then(res => console.log(res))
    .catch(err => console.error(err));

Advertisement

Answer

TL;DR – If a function that returns a promise throws an exception before returning the promise then that exception would have to be caught in a regular try-catch block.

Consider this function

function asyncAdd(x,y){
   if(x === 2){
        throw new Error("good old exception")
   }else if(x === 1) { 
      return Promise.reject("fancy exception")
   }

   return Promise.resolve(x+y)
}

This would print “Try caught good old exception”

try{
  asyncAdd(2,10).then(x =>console.log("result", x)).catch(y => console.error("Promise caught", y));
}catch (e){
  console.error("Try caught", e);
}

This would print “Promise caught fancy exception”

try{
  asyncAdd(1,10).then(x =>console.log("result", x)).catch(y => console.error("Promise caught", y));
}catch (e){
  console.error("Try caught", e);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement