How to Catch Unhandled Javascript Errors(如何捕获未处理的Javascript错误)
Assign the window.onerror
event to an event handler like:
(将window.onerror
事件分配给事件处理程序,如:)
<script type="text/javascript">
window.onerror = function(msg, url, line, col, error) {
// Note that col & error are new to the HTML 5 spec and may not be
// supported in every browser. It worked for me in Chrome.
var extra = !col ? '' : '
column: ' + col;
extra += !error ? '' : '
error: ' + error;
// You can view the information in an alert to see things working like this:
alert("Error: " + msg + "
url: " + url + "
line: " + line + extra);
// TODO: Report this error via ajax so you can keep track
// of what pages have JS issues
var suppressErrorAlert = true;
// If you return true, then error alerts (like in older versions of
// Internet Explorer) will be suppressed.
return suppressErrorAlert;
};
</script>
As commented in the code, if the return value of window.onerror
is true
then the browser should suppress showing an alert dialog.
(如代码中所述,如果window.onerror
的返回值为true
则浏览器应禁止显示警告对话框。)
When does the window.onerror Event Fire?(window.onerror什么时候发生火灾?)
In a nutshell, the event is raised when either 1.) there is an uncaught exception or 2.) a compile time error occurs.
(简而言之,当1.)存在未捕获的异常或2.)发生编译时错误时引发该事件。)
uncaught exceptions
(没有被捕的例外)
compile error
(编译错误)
-
<script>{</script>
-
<script>for(;)</script>
-
<script>"oops</script>
-
setTimeout("{", 10);
, it will attempt to compile the first argument as a script(,它将尝试将第一个参数编译为脚本)
Browsers supporting window.onerror(浏览器支持window.onerror)
- Chrome 13+
(Chrome 13+)
- Firefox 6.0+
(Firefox 6.0+)
- Internet Explorer 5.5+
(Internet Explorer 5.5+)
- Opera 11.60+
(Opera 11.60+)
- Safari 5.1+
(Safari 5.1+)
Screenshot:(截图:)
Example of the onerror code above in action after adding this to a test page:
(将此添加到测试页面后,上面的onerror代码示例:)
<script type="text/javascript">
call_something_undefined();
</script>
JSFiddle:(的jsfiddle:)
https://jsfiddle.net/nzfvm44d/
(https://jsfiddle.net/nzfvm44d/)
References:(参考文献:)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…