Caught rejected promise is reported as uncaught
Reported by
mathieu....@gmail.com,
May 24 2016
|
|||
Issue descriptionUserAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.54 Safari/537.36 Steps to reproduce the problem: 1. Assign rejected promise to variable "promise" 2. handle rejection using "promise.catch()" 3. Observe "Uncaught (in promise) Error" in the console. If handling the rejection using the "then" rejectionHandler second argument, or before assigning to a variable, everything works as expected. Reproduction code here: https://jsfiddle.net/c22svqh2/3/ What is the expected behavior? What went wrong? There should be no error in the console since the promise rejection is immediately handled. Did this work before? Yes Before unhandled rejections errors were reported? Chrome version: 51.0.2704.54 Channel: beta OS Version: 10.0 Flash Version:
,
May 24 2016
And the "window.onrejectionhandled" is never triggered either: https://jsfiddle.net/c22svqh2/6/
,
May 24 2016
,
May 24 2016
That's not a bug.
Consider this:
window.onunhandledrejection = function(error) {
console.log('Unhandled:', error.promise);
}
var promise = new Promise(function(resolve, reject) {
reject(new Error('Rejected'));
});
promise.then(function() {
console.log("Success !?");
});
promise.catch(function() {
console.log("caught.")
});
The console output would be:
caught.
uncaught
undefined:1 Uncaught (in promise) undefined
The reason is that Promise.prototype.then also creates a promise. If it does not define a reject handler, it attaches a default handler. But that counts as unhandled, since the rejected promise can still be passed on.
Now consider:
window.onunhandledrejection = function(error) {
console.log('Unhandled:', error.promise);
}
var promise = new Promise(function(resolve, reject) {
reject(new Error('Rejected'));
});
promise.then(function() {
console.log("Success !?");
}).catch(function() {
console.log("caught after then");
});
promise.catch(function() {
console.log("caught.")
});
Console output is now:
caught.
caught after then
,
May 24 2016
You're right, I was thinking that promises returned from .then shouldn't get reported if they don't get assigned to anything, but most of the time that's actually a programming error. It's safer to chain a .catch at the end anyway. |
|||
►
Sign in to add a comment |
|||
Comment 1 by mathieu....@gmail.com
, May 24 2016