user5526811
user5526811

Reputation:

Throwing new error in catch block doesn't work

I'm doing some async operations, and I'm using the native implementation of Promise to control the execution flow:

Promise.resolve({})
   .then(...)
   .then(...)
   .then(...)
   .catch((error) => { throw new Error(error) });

No error is being thrown, but when I changed to a console.log, everything worked. Any ideas why?

Thanks!

Upvotes: 1

Views: 2131

Answers (1)

solendil
solendil

Reputation: 8458

An exception raised in a promise chain can only be intercepted with a catch later in the same promise chain. It cannot be seen outside of the promise chain (if this was your intent.) In your example, the exception is "lost". However, Chrome and some other browsers detect this case and put a warning for an unhandled exception in the console.

A correct promise chain with exceptions would be:

Promise.resolve({})
   .then(...)
   .then(() => { throw new Error(error); }) // throw exception here
   .then(...) 
   .catch((error) => { /* handle error */ }); // catch it later in promise chain
   .then(...)
   .then(() => { throw new Error(error); }) // this exception is not caught later in the promise and is lost (shown as unhandled exception in some browsers)

Upvotes: 1

Related Questions