Following is an example:
var promise = new Promise(function(resolve, reject) {
throw new Error('test');
});
promise.catch(function(error) {
console.log(error + ' 1 ');
return error
}).catch(function(error) {
console.log(error + ' 2 ');
return error
})
The result for the codes are:
Error: test 1
As can be seen, the second catch call doesn't work. Does that mean Promise cannot handle error using the chain syntax of catch? Is there a way to pass the current error to the next catch() call?
Returning the error will not make it hit the next catch. You need to throw the error again:
promise.catch(function(error) {
console.log(error + ' 1 ');
throw error
}).catch(function(error) {
console.log(error + ' 2 ');
return error
})
-> Error: test 1
-> Error: test 2
You have to throw the error again, as opposed to just returning an error object:
var promise = new Promise(function(resolve, reject) {
throw new Error('test');
});
promise.catch(function(error) {
console.log(error + ' 1 ');
throw error
}).catch(function(error) {
console.log(error + ' 2 ');
return error
})
js has no internal notion of "this is an error object so throw it" - if there had been a then() clause following your first catch(), operation would have been deferred to that, like so:
var promise = new Promise(function(resolve, reject) {
throw new Error('test');
});
promise.catch(function(error) {
console.log(error + ' 1 ');
return error
}).then(function(error) {
console.log(error + ' 2 ');
return error
})
Hope this helps!
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