使用 bluebird 承诺的异步异常处理 [英] Asynchronous exception handling with bluebird promises
问题描述
处理这种情况的最佳方法是什么.我处于受控环境中,我不想崩溃.
What is the best way to handle this scenario. I am in a controlled environment and I don't want to crash.
var Promise = require('bluebird');
function getPromise(){
return new Promise(function(done, reject){
setTimeout(function(){
throw new Error("AJAJAJA");
}, 500);
});
}
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);
});
当从 setTimeout 中抛出时,我们将始终得到:
When throwing from within the setTimeout we will always get:
$ node bluebird.js
c:lp
plusbcodescratchboardluebird.js:6
throw new Error("AJAJAJA");
^
Error: AJAJAJA
at null._onTimeout (c:lp
plusbcodescratchboardluebird.js:6:23)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
如果抛出发生在 setTimeout 之前,那么 bluebirds catch 会捡起来:
If the throw occurs before the setTimeout then bluebirds catch will pick it up:
var Promise = require('bluebird');
function getPromise(){
return new Promise(function(done, reject){
throw new Error("Oh no!");
setTimeout(function(){
console.log("hihihihi")
}, 500);
});
}
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);
});
结果:
$ node bluebird.js
Error [Error: Oh no!]
这很棒 - 但是如何在节点或浏览器中处理这种性质的恶意异步回调.
Which is great - but how would one handle a rogue async callback of this nature in node or the browser.
推荐答案
Promises 不是 域a>,它们不会从异步回调中捕获异常.你不能那样做.
Promises are not domains, they will not catch exceptions from asynchronous callbacks. You just can't do that.
Promises 但是会捕获从 then
/catch
/Promise
构造函数回调中抛出的异常.所以用
Promises do however catch exceptions that are thrown from within a then
/ catch
/ Promise
constructor callback. So use
function getPromise(){
return new Promise(function(done, reject){
setTimeout(done, 500);
}).then(function() {
console.log("hihihihi");
throw new Error("Oh no!");
});
}
(或只是 Promise.delay
) 以获得所需的行为.永远不要抛出自定义(非承诺)异步回调,始终拒绝周围的承诺.如果确实需要,请使用 try-catch
.
这篇关于使用 bluebird 承诺的异步异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!