问题描述
有没有办法全局捕获所有异常,包括 Promise 异常.示例:
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);
// });
这个脚本会无声无息地死掉.firebug 中什么都没有.
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?
推荐答案
更新,原生 Promise 现在在大多数浏览器中执行以下操作:
Update, native promises now do the following in most browsers:
window.addEventListener("unhandledrejection", function(promiseRejectionEvent) {
// handle error here, for example log
});
我们前几天刚刚讨论过这个问题.
We were just discussing this the other day.
以下是使用 bluebird 执行此操作的方法:
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
}
对于 Bluebird,还可以使用 Promise.onPossivelyUnhandledRejection
.不需要 done
的调用,因为与 Q 不同,库会检测未处理的拒绝本身(更新 2016 - 我现在为 Q 编写了代码,它会这样做).
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).
至于本机承诺 - 它们将最终报告给 window.onerror 或新的处理程序,但规范过程尚未完成 - 您可以在这里关注.
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.
这篇关于如何在 Promise 中捕获未捕获的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!