Home > Back-end >  How to handle errors using `.catch` in promises
How to handle errors using `.catch` in promises

Time:05-25

I want to continue code execution when my promises do not have errors, If there are any errors however, I do not want to proceed. How do I gracefully handle this case ?

Eg.

/* start of REST call */
const resultA = fetchThings()
    .then(things => returnSomeResult(things))
    .then(...)
    ...
    .catch(err => throw err);  // cannot proceed computation if there is error
    
const resultB = fetchOtherThings()
    .then(otherTings => returnOtherResult(otherThings))
    .then(...)
    ...
    .catch(err => throw err); // cannot proceed if there is error

const resultC = Promise.all([resultA, resultB]) => { // do other stuff }

// return resultC from REST call if successful

When an error occurs in either of the results, I am getting a UnhandledPromiseRejectionWarning on the terminal. It states that This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with a .catch(). I suspect it is because I am throwing the error inside the catch block.

However, I don't want the code to proceed when there is an error from either resultA or resultB.

How can I better handle this scenario of mine ?

CodePudding user response:

My guess would be that you're not handling errors thrown by Promise.all(), which will be rejected if any of the promises it's handling will be rejected.

So you need to catch errors there as well:

Promise.all(…).then(…).catch(e => …)

FWIW, your catch()'s are superfluous:

.catch(err => throw err)

You're catching errors that were thrown and rethrowing them, which isn't necessary (they will be caught by .catch() that you'll attach to Promise.all()).

  • Related