Yes!!
Promise 中的错误传播是它的最强项之一。它的行为与同步代码完全相同。
try {
throw new Error("Hello");
} catch (e){
console.log('Caught here, when you catch an error it is handled');
}
非常类似于:
Promise.try(function(){
throw new Error("Hello");
}).catch(function(e){
console.log('Caught here, when you catch an error it is handled');
});
就像在顺序代码中一样,如果您想对错误执行一些逻辑但不将其标记为已处理 - 您可以重新抛出它:
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
}
变成:
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
});
请注意,在 Bluebird 中,您可以进行类型捕获和条件捕获,因此,如果您所做的只是if
根据承诺的类型或内容来决定是否处理它 - 您可以保存它。
var p = Promise.try(function(){
throw new IOError("Hello");
}).catch(IOError, function(e){
console.log('Only handle IOError, do not handle syntax errors');
});
您还可以使用.error
处理OperationalError
源自承诺的 API。一般来说OperationalError
表示可以恢复的错误(相对于程序员错误)。例如:
var p = Promise.try(function(){
throw new Promise.OperationalError("Lol");
}).error(function(e){
console.log('Only handle operational errors');
});
这样做的好处是不静音TypeError
代码中的错误或语法错误,这在 JavaScript 中可能很烦人。