MikeWyatt
MikeWyatt

Reputation: 7871

Exceptions thrown in jQuery AJAX callbacks swallowed?

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 );
    }               
} );

Upvotes: 7

Views: 4595

Answers (3)

Tinister
Tinister

Reputation: 11487

If you take a look at the non-minified version of jQuery 1.4.2, the relevant lines are 5264 through 5274:

function success() {
    // If a local callback was specified, fire it and pass it the data
    if ( s.success ) {
        s.success.call( callbackContext, data, status, xhr );
    }

    // Fire the global callback
    if ( s.global ) {
        trigger( "ajaxSuccess", [xhr, s] );
    }
}

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.

Upvotes: 8

Peter Bailey
Peter Bailey

Reputation: 105898

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

Upvotes: 0

Justin Ethier
Justin Ethier

Reputation: 134177

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.

Upvotes: 1

Related Questions