Exceptions thrown in jQuery AJAX callbacks swallowed?
ajax, exception, javascript, jquery
Solution
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.
Problem
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 ); } } ); ```