javascript jQuery:全局异常处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14374719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: global exception handler
提问by flybywire
Possible Duplicate:
JavaScript Exception Handling
可能的重复:
JavaScript 异常处理
I have a web application where 100% of the javascript code executes as jQuery event handlers (I guess most jQuery apps are like this).
我有一个 web 应用程序,其中 100% 的 javascript 代码作为 jQuery 事件处理程序执行(我猜大多数 jQuery 应用程序都是这样)。
The question is how can I define a global exception handler. That is, if a function that is called when any exception that happens within any jQuery event handler goes uncaught (whether it is onload, click, a succesfull ajax call, an ajax error, whatever). My function would receive the error info (exception, stacktrace, whatever).
问题是如何定义全局异常处理程序。也就是说,如果在任何 jQuery 事件处理程序中发生任何异常时调用的函数未被捕获(无论是 onload、click、成功的 ajax 调用、ajax 错误,等等)。我的函数会收到错误信息(异常、堆栈跟踪等)。
Clarification:I don't mean globally catching in ajax problems generated by the server or network, but globally catching problems that are due to (presumably) bugs in our code.
澄清:我的意思不是全局捕获由服务器或网络生成的 ajax 问题,而是全局捕获由(大概)代码中的错误引起的问题。
采纳答案by Minko Gechev
I guess this can be achieved using concepts from the Aspect-oriented programming.
我想这可以使用面向方面的编程中的概念来实现。
We can simply create a wrapper of jQuery.event.dispatch
which will handle the errors:
我们可以简单地创建一个包装器来jQuery.event.dispatch
处理错误:
(function () {
var temp = jQuery.event.handle;
jQuery.event.handle = function () {
try {
temp.apply(this, arguments);
} catch (e) {
console.log('Error while dispatching the event.');
}
}
}());
$(document).click(function () {
throw 'Some error...';
});
Using this approach you must be very careful because of changes in the internal interface
使用这种方法你必须非常小心,因为内部接口的变化
- Note the example above works for jQuery v1.6.3, in jQuery 1.7.1
jQuery.event.dispatch
instead ofjQuery.event.handle
.
- 请注意,上面的示例适用于 jQuery v1.6.3,在 jQuery 1.7.1
jQuery.event.dispatch
而不是jQuery.event.handle
.
回答by Romain Meresse
You can use window.onerror
: https://developer.mozilla.org/en-US/docs/DOM/window.onerror
您可以使用window.onerror
:https: //developer.mozilla.org/en-US/docs/DOM/window.onerror
window.onerror = function errorHandler(msg, url, line) {
console.log(arguments);
// Just let default handler run.
return false;
}