13

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.

Community
  • 1
  • 1
flybywire
  • 261,858
  • 191
  • 397
  • 503

2 Answers2

15

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;
}
Romain Meresse
  • 3,044
  • 25
  • 29
  • 2
    this almost never works. :) `Note that some/many error events do not trigger window.onerror, you have to listen for them specifically` they said. – mayankcpdixit Jun 15 '15 at 14:13
  • @mayankcpdixit [Works for me](https://jsfiddle.net/5mpL7u0p/). Can you cite an example of something that doesn't get caught? – doug65536 Jul 20 '16 at 07:52
  • Modern style [works too](https://jsfiddle.net/5mpL7u0p/1/). – doug65536 Jul 20 '16 at 07:54
  • 2
    Well for example: If you are using Angular, errors wont pass through `window.onerror`. You have to handle them using factory. `window.onerror` is not triggered when the console directly generates an error. – mayankcpdixit Jul 24 '16 at 11:14
  • jQuery.Deferred exception won't be caught by this – jsaddwater May 05 '17 at 12:58
  • Good solution. One remark: there should be a semicolon after closing curly bracket, because this is an assignment statement. – Dawid Ohia Feb 04 '21 at 08:48
3

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.
Minko Gechev
  • 25,304
  • 9
  • 61
  • 68