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.
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;
}
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
jQuery.event.dispatch
instead of jQuery.event.handle
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With