使用 Bluebird Promises 进行异步异常处理
问:如何使用 Bluebird Promises 处理异步回调中未处理的异常?
Bluebird Promise 本质上不会捕获异步回调抛出的异常,这与domains.
A:使用 Promise 构造函数或 then() 闭包处理异常
要捕获异步回调中的异常,请将回调包装在 Promise 构造函数或 then( ) 闭包:
function getPromise(){
return new Promise(function(done, reject){
setTimeout(function(){
throw new Error("AJAJAJA");
}, 500);
}).then(function() {
console.log("hihihihi");
throw new Error("Oh no!");
});
}
避免在自定义异步回调中抛出异常
永远不要在自定义异步回调中直接抛出异常(在 Promise 回调之外)。相反,拒绝周围的承诺:
function getPromise(){
return new Promise(function(done, reject){
setTimeout(done, 500);
}).then(function() {
console.log("hihihihi");
reject(new Error("Oh no!"));
});
}
示例
使用 Promise 构造函数:
var p = getPromise();
p.then(function(){
console.log("Yay");
}).error(function(e){
console.log("Rejected",e);
}).catch(Error, function(e){
console.log("Error",e);
}).catch(function(e){
console.log("Unknown", e);
});
输出:
Error [Error: Oh no!]
此方法可确保捕获并正确处理异常,防止应用程序崩溃。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3