Lee Francis
Lee Francis

Reputation: 557

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!

Upvotes: 18

Views: 9245

Answers (5)

Dave Becker
Dave Becker

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

Sam
Sam

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

user2043553
user2043553

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

Linus Thiel
Linus Thiel

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

faino
faino

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

Related Questions