Reputation: 557
I'm using jQuery.ajax() to connect to my back end service. I have configured an error() handler and a statusCode() handler. They both work fine, but when my statusCode handler gets fired the error handler also fires (the error handler is actually fired first). I would prefer this not to happen. I am assuming this is possible without having to hack the error handler code?
My code looks something like this:
$.ajax({
...
error: function(...) {
// process a general type of error here
},
statusCode: {
401: function() {
// process a specific authentication failure
}
}
});
So how can I avoid the error() handler firing when the HTTP status code is 401?
Thanks for bothering to read!
Upvotes: 18
Views: 9245
Reputation: 1433
You can easily check the status code inside the error callback. The first parameter should be XMLHttpRequest
(or jqHXR
depeding on your version of jQuery) object. Check the 'status' property for the status code of the error handle accordingly.
E.g.
error: function(a, b, c){
if(a.status != 401){
// handle other errors except authentication
}
}
Upvotes: 12
Reputation: 116
Improving on the previous workarounds that require hard coding the status codes for which you do not want to fire the generic event handler.
In my opinion it is safer to edit your error handler since beforeSend might get overwritten for some other purpose and you can therefore inadvertently fire the generic error handler on those calls. (If someone overwrites the error callback they expect it to affect the error handling, if they modify the beforeSend callback they do not).
So you would get:
function ajaxError (jqXHR, textStatus, errorThrown)
{
if (jqXHR.status in this.statusCode) return;
// Handle generic events here.
}
Upvotes: 6
Reputation: 161
You can try using ajaxSetup and beforeSend to tweak the error handler of your ajax request automatically:
$.ajaxSetup({
beforeSend: function(jqXHR, settings) {
if (typeof settings.error === 'function') {
var errorfunc = settings.error;
settings.error = function(jqXHR2, textStatus, errorThrown) {
if (jqXHR2.status !== 401) errorfunc(jqXHR2, textStatus, errorThrown);
};
}
}
});
In my case this works.
Upvotes: 2
Reputation: 39261
Without hacking jQuery.ajax
, you can't. To me, jQuery's ajax methods is one of the sore points of the library. For more sensible request handling, I recommend you look into superagent or some other stand-alone library.
Upvotes: 7
Reputation: 3224
Check out the answer in this post about handling status codes with the error method: how to get jquery ajax status code
Upvotes: 0