我正在尝试向我的网站添加一个 onerror 事件。
window.onerror = function() {
alert("an error");
}
但我收到的只是:
notThere();
ReferenceError: notThere is not defined
我错过了什么?
浏览器:Chrome 26.0.1410.64 m
重现步骤:
- 将代码添加到控制台。
- 将 notThere() 添加到控制台
我正在尝试向我的网站添加一个 onerror 事件。
window.onerror = function() {
alert("an error");
}
但我收到的只是:
notThere();
ReferenceError: notThere is not defined
我错过了什么?
浏览器:Chrome 26.0.1410.64 m
重现步骤:
控制台直接产生错误时不会触发window.onerror。它可以通过触发setTimeout
,例如,setTimeout(function() { notThere(); }, 0);
Chrome 中的window.onerror
作品(参见 jsfiddle - http://jsfiddle.net/PWSDF/),但显然不在控制台中 - 这是有道理的。
您可能无法处理错误的其他一些原因window.onerror
(除了提到的错误):
window.onerror
在你之后。如果您使用的是 Angular,则错误不会通过window.onerror
. 你必须使用这个工厂来处理它们:
.factory('$exceptionHandler', function() {
return function errorCatcherHandler(exception, cause) {
console.error(exception);
if (window.OnClientError) window.OnClientError(exception);
};
})
看:
https://docs.angularjs.org/api/ng/service/ $exceptionHandler
http://bahmutov.calepin.co/catch-all-errors-in-angular-app.html