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

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


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  }}


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.


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