jskidd3
jskidd3

Reputation: 4783

How to determine which promise throws error (in a promise chain)

How can I determine which of the three promises caused the error?

The code below is pseudo, but in my actual code I am working with third-party libraries (Stripe and Firebase) and therefore I cannot modify the actual Promises themselves.

I thought that I could check to see if the error argument in the catch contains a specific value (e.g. in Stripe there's a very detailed error object), but surely there must be a better way.

return async.func.one.doIt()
  .then(() => {
    return async.func.two.doIt();
  })
  .then(() => {
    return async.func.three.doIt();
  })
  .then(() => {
    return { success: true };
  })
  .catch((error) => {
    // How do I know which 'then' caused
    // the catch to invoke?
  });

Upvotes: 1

Views: 110

Answers (2)

mhd saeed shamborsh
mhd saeed shamborsh

Reputation: 113

you can change your code to this return func.one.doIt() .then(() => { return async.func.two.doIt().then(() => { return async.func.three.doIt().then(() => { return { success: true }; }).catch((error) => { // How do I know which 'then' caused // the catch to invoke? });; }).catch((error) => { // How do I know which 'then' caused // the catch to invoke? }); }).catch((error) => { // How do I know which 'then' caused // the catch to invoke? });

Upvotes: 0

Mateusz
Mateusz

Reputation: 91

You can put '.catch' between each '.then' method to catch error. It should catch closest error that was thrown by any of previous promises, up to next '.catch' method.

Upvotes: 2

Related Questions