Reputation: 2723
I'm trying to implement a jQuery default HTTP error handler for AJAX calls. I've implemented the default error handler for generic application errors as follows:
$(document).ajaxError(function(event, jqXHR, settings, thrownError) {
switch (jqXHR.status) {
case 403:
console.log('Forbidden, go away!');
break;
case 404:
console.log('Resource not found :O');
break;
case 422:
console.log('Unprocessable entity.');
break;
case 500:
console.log('Someone have to pay for this!');
break;
default:
console.log('Anyone knows what is going on here?');
}
});
Now what i would like to achieve is to override a specific status code within a single AJAX call. Like for example
$.ajax({
...
error: function(jqXHR, textStatus, errorThrown) {
if(jqXHR.status === 404){
console.log('The requested unicorn is actually missing');
}
}
})
Right now, if i implement as shown above, both messages will be displayed
>The requested unicorn is actually missing
>Resource not found :O
while i'm trying only to get The requested unicorn is actually missing
message.
Setting global: false
flag in the single AJAX call settings implies ignoring all global AJAX functions within that AJAX call and unfortunately that is not a viable solution for my application.
Any idea? Thanks!
Upvotes: 3
Views: 1973
Reputation: 926
you can do the following
$.ajax({
handleErrors: [404],
...
error: function(jqXHR, textStatus, errorThrown) {
if(jqXHR.status === 404){
console.log('The requested unicorn is actually missing');
}
}
});
then in your global handler check if the error is handled
$(document).ajaxError(function(event, jqXHR, settings, thrownError) {
if (settings.handleErrors && settings.handleErrors.indexOf(jqXHR.status) !== -1) {
return;
}
switch (jqXHR.status) {
case 403:
console.log('Forbidden, go away!');
break;
case 404:
console.log('Resource not found :O');
break;
case 422:
console.log('Unprocessable entity.');
break;
case 500:
console.log('Someone have to pay for this!');
break;
default:
console.log('Anyone knows what is going on here?');
}
});
Upvotes: 5