如何在承诺中捕捉未被捕获的例外 [英] How to catch uncaught exception in Promise
问题描述
window.onerror = function myErrorHandler(errorMsg,url,lineNumber){
alert(Error occurredured: + errorMsg); //或任何消息
返回false;
}
var myClass = function(){
}
var pr = new Promise(function ,反应){
var myInstance = new myClass();
myInstance.undefinedFunction(); //这将抛出异常
resolve(myInstance);
});
pr.then(function(result){
console.log(result);
});
//我知道这将是:
// pr.then(function(result){
// console.log(result);
/ /})。catch(function(e){
// console.log(e);
//});
此脚本将无声地死机。
我的问题是,如果我犯了一个错误,忘了抓住它有没有办法在全球范围内捕捉?
更新,本机承诺现在在大多数浏览器中执行以下操作:
window.addEventListener(unhandledrejection,function(err,promise){
// handle error here,例如log
});
我们只是在另一天讨论这个。 / p>
这是蓝鸟如何做到这一点:
窗口.onpossununhandledexception = function(){
window.onerror.apply(this,arguments); // call
}
window.onerror = function(err){
console.log(err); //记录所有错误
}
使用Bluebird也可以使用 Promise.onPossiblyUnhandledRejection
。不需要调用完成
,因为库将检测到未处理的拒绝本身不同于Q(UPDATE 2016 - 我现在为Q编写了代码,这样做)。
对于本机承诺 - 他们将最终报告给window.onerror或一个新的处理程序,但是规范过程还没有完成 - 你可以请在这里。
Is there any way to globally catch all exceptions including Promise exceptions. Example:
window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
alert("Error occured: " + errorMsg);//or any message
return false;
}
var myClass = function(){
}
var pr = new Promise(function(resolve, react){
var myInstance = new myClass();
myInstance.undefinedFunction(); // this will throw Exception
resolve(myInstance);
});
pr.then(function(result){
console.log(result);
});
// i know right will be this:
// pr.then(function(result){
// console.log(result);
// }).catch(function(e){
// console.log(e);
// });
This script will silently die without error. Nothing in firebug.
My question is if I do a mistake and forgot to catch it is there any way to catch it globally?
Update, native promises now do the following in most browsers:
window.addEventListener("unhandledrejection", function(err, promise) {
// handle error here, for example log
});
We were just discussing this the other day.
Here is how you'd do this with bluebird:
window.onpossiblyunhandledexception = function(){
window.onerror.apply(this, arguments); // call
}
window.onerror = function(err){
console.log(err); // logs all errors
}
With Bluebird it's also possible to use Promise.onPossiblyUnhandledRejection
. The calls for done
are not needed as the library will detect unhandled rejection itself unlike Q (UPDATE 2016 - I now wrote code for Q and it does this).
As for native promises - they will eventually report to either window.onerror or a new handler but the specification process is not yet done - you can follow it here.
这篇关于如何在承诺中捕捉未被捕获的例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!