I’m using $(document).ajaxError() to catch server-side and communication errors in ajax calls.
What’s a good clean way to globally catch client-side errors (for logging purposes) in ajax javascript handlers? Overriding $.ajax()?
E.g.
$.get("http://foo.com/", function(){
alert(undefined.something); // I want this exception to be logged
});
I want to avoid writing individual try…catch…log for all my ajax handlers.
The only thing that comes to my mind is binding such
errorevent:$.activeshows the number of active Ajax requests, so error will fire even if the request returns success but hasundefined.somethingproblem in the success handler.DEMO: http://jsfiddle.net/KWX4k/
UPDATED: My test cases from the DEMO
I. Valid Ajax request with problem in success handler:
Result: fires!
II. Invaid Ajax request without problem in success handler:
Result: does not fire.
III. Simple undefined error in the code:
Result: does not fire.
So, it seems to be working 🙂
However in this method I see a small drawback. Since Ajax is usually used in asynchronous way, the event will fire twice if you have two errors – in Ajax handler and in the method which calls this Ajax request (i.e. placed immediately after calling Ajax). However, such situations are not important, since all actions after Ajax request are usually transferred to Ajax success handler.