Reputation: 28374
Is it possible to have errors bubble up in Promises?
See the code below for reference, I'd like to get promise1.catch
to catch the error generated in promise2
(which current does not work with this code):
function test() {
var promise1 = new Promise(function(resolve1) {
var promise2 = new Promise(function(resolve2) {
throw new Error('Error in promise2!');
});
promise2.catch(function(error2) {
console.log('Caught at error2', error2);
});
});
promise1.catch(function(error1) {
console.log('Caught at error1', error1);
});
}
test();
Upvotes: 3
Views: 1955
Reputation: 276386
Error propagation in promises is one of its strongest suits. It acts exactly like in synchronous code.
try {
throw new Error("Hello");
} catch (e){
console.log('Caught here, when you catch an error it is handled');
}
Is very similar to:
Promise.try(function(){
throw new Error("Hello");
}).catch(function(e){
console.log('Caught here, when you catch an error it is handled');
});
Just like in sequential code, if you want to do some logic to the error but not mark it as handled - you rethrow it:
try {
throw new Error("Hello");
} catch (e){
console.log('Caught here, when you catch an error it is handled');
throw e; // mark the code as in exceptional state
}
Which becomes:
var p = Promise.try(function(){
throw new Error("Hello");
}).catch(function(e){
console.log('Caught here, when you catch an error it is handled');
throw e; // mark the promise as still rejected, after handling it.
});
p.catch(function(e){
// handle the exception
});
Note that in Bluebird you can have typed and conditional catches, so if all you're doing is an if
on the type or contents of the promise to decide whether or not to handle it - you can save that.
var p = Promise.try(function(){
throw new IOError("Hello");
}).catch(IOError, function(e){
console.log('Only handle IOError, do not handle syntax errors');
});
You can also use .error
to handle OperationalError
s which originate in promisified APIs. In general OperationalError
signifies an error you can recover from (vs a programmer error). For example:
var p = Promise.try(function(){
throw new Promise.OperationalError("Lol");
}).error(function(e){
console.log('Only handle operational errors');
});
This has the advantage of not silencing TypeError
s or syntax errors in your code, which can be annoying in JavaScript.
Upvotes: 7