有没有办法全局捕获所有异常,包括 Promise 异常。示例:
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 中没有任何内容。
我的问题是,如果我犯了一个错误而忘了捕捉它,有没有办法在全局范围内捕捉它?
最佳答案
更新,原生 promise 现在在大多数浏览器中执行以下操作:
window.addEventListener("unhandledrejection", function(promiseRejectionEvent) {
// handle error here, for example log
});
前几天我们刚讨论过这个。
这里是你如何用 bluebird 做到这一点:
window.onpossiblyunhandledexception = function(){
window.onerror.apply(this, arguments); // call
}
window.onerror = function(err){
console.log(err); // logs all errors
}
对于 Bluebird,还可以使用 Promise.onPossiblyUnhandledRejection
。不需要对 done
的调用,因为库将检测未处理的拒绝本身,这与 Q 不同(更新 2016 - 我现在为 Q 编写代码并且它执行此操作)。
至于原生 promise - 它们将最终报告给 window.onerror 或新的处理程序,但规范过程尚未完成 - 你可以 follow it here .
关于javascript - 如何在 Promise 中捕获未捕获的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28001722/