Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: global exception handler [duplicate]

Possible Duplicate:
JavaScript Exception Handling

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

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

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.

like image 318
flybywire Avatar asked Jan 17 '13 08:01

flybywire


2 Answers

You can use 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;
}
like image 160
Romain Meresse Avatar answered Nov 16 '22 14:11

Romain Meresse


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:

(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 of jQuery.event.handle.
like image 38
Minko Gechev Avatar answered Nov 16 '22 14:11

Minko Gechev