Jquery Catch Any Ajax Error
i like to catch any ajax 401 Unauthorised exception, but do no like to change all my ajax queries. Is there a way to change it for any $.ajax call like (overwrite any error handler
Solution 1:
you can use the global ajax event handlers .ajaxError()
$( document ).ajaxError(function( event, jqxhr, settings, exception ) {
if ( jqxhr.status== 401 ) {
$( "div.log" ).text( "Triggered ajaxError handler." );
}
});
Solution 2:
You can do something like this:
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 401) {
alert('HTTP Error 401 Unauthorized.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
This will catch error in any of your ajax
calls.
Solution 3:
The $.ajaxSetup()
function will allow you to specify global options for Ajax calls. Be careful however as other calls to ajaxSetup()
will overwrite global options and specified local options to the ajax()
method will override global settings.
Solution 4:
Try using .ajaxError()
as a global method http://api.jquery.com/ajaxError/
Solution 5:
To catch a 401
status code simply add
$.ajaxSetup({
statusCode: {
401: function(err){
console.log('Login Failed.', err.responseJSON);
// or whatever...
}
}
});
to your page somewhere before the AJAX call is fired.
Post a Comment for "Jquery Catch Any Ajax Error"