Search code examples
jqueryajaxerror-handlinghttp-status-codes

jQuery ajax - avoiding error() callback when statusCode() callback invoked


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!


Solution

  • 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.