jQuery:全局异常处理程序 [英] jQuery: global exception handler

查看:130
本文介绍了jQuery:全局异常处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

JavaScript异常处理

我有一个Web应用程序,其中100%的javascript代码执行为jQuery事件处理程序(我猜大多数jQuery应用程序都是这样的)。

I have a web application where 100% of the javascript code executes as jQuery event handlers (I guess most jQuery apps are like this).

问题是如何定义一个全局异常处理程序。也就是说,如果在任何jQuery事件处理程序中发生的任何异常都被忽略(无论是onload,click,一个成功的ajax调用,一个ajax错误,无论如何)调用的函数。
我的函数将收到错误信息(异常,stacktrace,无论如何)。

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).

澄清:我不是全局捕捉服务器或网络产生的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.

推荐答案

我想这可以使用面向方面的编程

我们可以简单地创建一个包装器 jQuery.event.dispatch 将处理错误:

We can simply create a wrapper of jQuery.event.dispatch which will handle the errors:

(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


  • 注意上面的例子适用于jQuery v1.6.3,在jQuery 1.7.1 jQuery.event.dispatch 而不是 jQuery.event.handle

  • Note the example above works for jQuery v1.6.3, in jQuery 1.7.1 jQuery.event.dispatch instead of jQuery.event.handle.

这篇关于jQuery:全局异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆