有没有一种方法可以全局捕获所有异常,包括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);
// });
这个脚本会在不报错的情况下默默死掉。火狐浏览器调试工具中也看不到任何信息。
我的问题是,如果我犯了一个错误并忘记捕获它,是否有全局捕获的方法?
window.addEventListener("unhandledrejection", function (event){})
就行了。http://bluebirdjs.com/docs/api/error-management-configuration.html#global-rejection-events -- 我可能理解文档有误,但它听起来像是bluebird现在会为你触发一个unhandledrejection
事件。 - Devin Rhode