views:

131

answers:

3

Is there any way to handle exceptions thrown from AJAX callbacks in jQuery, other than adding a try..catch block to each callback? The error function is not called in this situation.

$.ajax(
{
    url: 'myurl.rails',
    success: function( data )
    {
        throw 'Oh no!';
    },
    error: function ( xhr, textStatus, errorThrown )
    {
        console.log( 'AJAX call failed', xhr, textStatus, errorThrown );
    }               
} );
A: 

Have you looked into any of the global AJAX features of jQuery such as ajaxSetup and ajaxError?

Peter Bailey
As Justin mentioned, the error/ajaxError callback is for failed requests, not for exceptions thrown in application code in the success callback.
MikeWyatt
A: 

The error callback is designed to be used when there is a problem with the request itself. According to the docs:

A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

So, if instead there is a problem with the data you get back, then you should deal with it within the success callback - perhaps by logging it to console, or notifying the user.

Justin Ethier
I use quite a bit of AJAX in my site, and wrapping every single success callback in a try..catch block with logging isn't ideal.
MikeWyatt
Are there specific types of errors that you are seeing on your site? What exactly are you seeing, and what are you planning to do once you detect an error?
Justin Ethier
I just want to log whatever exceptions might be thrown. The specific exception type doesn't matter, other than it being unexpected.
MikeWyatt
A: 

If you take a look at the non-minified version of jQuery 1.4.2, the relevant lines are 5264 through 5274. jQuery just calls the success function applied to settings object (if it exists) without any care of what the function returns or throws.

What you can do instead is use jQuery.ajaxSetup() like so:

jQuery.ajaxSetup({
    success: function() {
        try {
            if ( this.mysuccess ) {
                this.mysuccess.apply( this, arguments );
            }
        }
        catch(err) {
            // whatever
        }
    }
});

And use mysuccess (or whatever you would prefer to call it) instead of success at the individual jQuery.ajax calls.

Tinister