catch successfully handles the error: // the execution: catch -> then new Promise((resolve, reject) => { throw new Error("Whoops!"); }). catch(function(error) { alert("The error is handled, continue normally"); }).
If you throw an error inside the promise, the catch() method will catch it, not the try/catch. In this example, if any error in the promise1, promise2, or promise4, the catch() method will handle it.
catch : when a promise fails, you catch the error, and do something with the error information. finally : when a promise settles (fails or passes), you can finally do something.
catch() The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.
As others have explained, the "black hole" is because throwing inside a .catch
continues the chain with a rejected promise, and you have no more catches, leading to an unterminated chain, which swallows errors (bad!)
Add one more catch to see what's happening:
do1().then(do2).catch(function(err) {
//console.log(err.stack); // This is the only way to see the stack
throw err; // Where does this go?
}).catch(function(err) {
console.log(err.stack); // It goes here!
});
A catch in the middle of a chain is useful when you want the chain to proceed in spite of a failed step, but a re-throw is useful to continue failing after doing things like logging of information or cleanup steps, perhaps even altering which error is thrown.
To make the error show up as an error in the web console, as you originally intended, I use this trick:
.catch(function(err) { setTimeout(function() { throw err; }); });
Even the line numbers survive, so the link in web console takes me straight to the file and line where the (original) error happened.
Any exception in a function called as a promise fulfillment or rejection handler gets automatically converted to a rejection of the promise you're supposed to return. The promise code that calls your function takes care of this.
A function called by setTimeout on the other hand, always runs from JavaScript stable state, i.e. it runs in a new cycle in the JavaScript event loop. Exceptions there aren't caught by anything, and make it to the web console. Since err
holds all the information about the error, including the original stack, file and line number, it still gets reported correctly.
Important things to understand here
Both the then
and catch
functions return new promise objects.
Either throwing or explicitly rejecting, will move the current promise to the rejected state.
Since then
and catch
return new promise objects, they can be chained.
If you throw or reject inside a promise handler (then
or catch
), it will be handled in the next rejection handler down the chaining path.
As mentioned by jfriend00, the then
and catch
handlers are not executed synchronously. When a handler throws, it will come to an end immediately. So, the stack will be unwound and the exception would be lost. That is why throwing an exception rejects the current promise.
In your case, you are rejecting inside do1
by throwing an Error
object. Now, the current promise will be in rejected state and the control will be transferred to the next handler, which is then
in our case.
Since the then
handler doesn't have a rejection handler, the do2
will not be executed at all. You can confirm this by using console.log
inside it. Since the current promise doesn't have a rejection handler, it will also be rejected with the rejection value from the previous promise and the control will be transferred to the next handler which is catch
.
As catch
is a rejection handler, when you do console.log(err.stack);
inside it, you are able to see the error stack trace. Now, you are throwing an Error
object from it so the promise returned by catch
will also be in rejected state.
Since you have not attached any rejection handler to the catch
, you are not able to observe the rejection.
You can split the chain and understand this better, like this
var promise = do1().then(do2);
var promise1 = promise.catch(function (err) {
console.log("Promise", promise);
throw err;
});
promise1.catch(function (err) {
console.log("Promise1", promise1);
});
The output you will get will be something like
Promise Promise { <rejected> [Error: do1] }
Promise1 Promise { <rejected> [Error: do1] }
Inside the catch
handler 1, you are getting the value of promise
object as rejected.
Same way, the promise returned by the catch
handler 1, is also rejected with the same error with which the promise
was rejected and we are observing it in the second catch
handler.
I tried the setTimeout()
method detailed above...
.catch(function(err) { setTimeout(function() { throw err; }); });
Annoyingly, I found this to be completely untestable. Because it's throwing an asynchronous error, you can't wrap it inside a try/catch
statement, because the catch
will have stopped listening by the time error is thrown.
I reverted to just using a listener which worked perfectly and, because it's how JavaScript is meant to be used, was highly testable.
return new Promise((resolve, reject) => {
reject("err");
}).catch(err => {
this.emit("uncaughtException", err);
/* Throw so the promise is still rejected for testing */
throw err;
});
According the spec (see 3.III.d):
d. If calling then throws an exception e,
a. If resolvePromise or rejectPromise have been called, ignore it.
b. Otherwise, reject promise with e as the reason.
That means that if you throw exception in then
function, it will be caught and your promise will be rejected. catch
don't make a sense here, it is just shortcut to .then(null, function() {})
I guess you want to log unhandled rejections in your code. Most promises libraries fires a unhandledRejection
for it. Here is relevant gist with discussion about it.
Yes promises swallow errors, and you can only catch them with .catch
, as explained more in detail in other answers. If you are in Node.js and want to reproduce the normal throw
behaviour, printing stack trace to console and exit process, you can do
...
throw new Error('My error message');
})
.catch(function (err) {
console.error(err.stack);
process.exit(0);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With