admin管理员组

文章数量:1279145

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

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 );
    }               
} );
Share Improve this question asked Apr 27, 2010 at 14:22 MikeWyattMikeWyatt 7,87111 gold badges53 silver badges71 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

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.

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.

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

本文标签: javascriptExceptions thrown in jQuery AJAX callbacks swallowedStack Overflow