33

We have an API which uses proper HTTP status codes for errors, and responds with JSON-encoded responses and appropriate Content-Type header. My situation is that jQuery.ajax() triggers the error callback when it encounters an HTTP error status, and not the success callback, so even when we have an intelligible JSON response, we have to resort to something like this:

$.ajax({
    // ...
    success: function(response) {
        if (response.success) {
            console.log('Success!');
            console.log(response.data);
        } else {
            console.log('Failure!');
            console.log(response.error);
        }
    },
    error: function(xhr, status, text) {
        var response = $.parseJSON(xhr.responseText);

        console.log('Failure!');

        if (response) {
            console.log(response.error);
        } else {
            // This would mean an invalid response from the server - maybe the site went down or whatever...
        }
    }
});

Is there a better paradigm than doing identical error handling in two spots in each jQuery.ajax() call? It's not very DRY, and I'm sure I've just missed something somewhere on good error handling practices in these cases.

FtDRbwLXw6
  • 27,774
  • 13
  • 70
  • 107
  • I'm assuming by HTTP Status code, you mean you are sending back 501 as the HTTP status code on error. Why would you do that if you are properly handling the error on the server side? – Lawrence Johnson Oct 04 '12 at 19:48
  • Check out the jquery.ajax (http://api.jquery.com/jQuery.ajax/) statusCode parameter. – ron tornambe Oct 04 '12 at 19:50
  • 3
    @LawrenceJohnson: I'm using the response codes as they were meant to be used. Sending a 200 OK every response would require reinventing the wheel with respect to error codes/messages. – FtDRbwLXw6 Oct 05 '12 at 02:16
  • 1
    Yes, but those errors are in the protocol at the network level. You've lost your mind if you think validation errors are the same as Http errors. – Lawrence Johnson Nov 09 '12 at 22:09
  • @Liam: Nothing in my question has anything to do with how to get response codes out of jQuery.ajax(). – FtDRbwLXw6 Mar 25 '14 at 16:40
  • why not make use of the error callback to return intelligible json response? – Fuseteam Jul 29 '20 at 22:45

1 Answers1

45

Check out jQuery.ajaxError()

It catches global Ajax errors which you can handle in any number of ways:

if (jqXHR.status == 500) {
  // Server side error
} else if (jqXHR.status == 404) {
  // Not found
} else if {
    ...

Alternatively, you can create a global error handler object yourself and choose whether to call it:

function handleAjaxError(jqXHR, textStatus, errorThrown) {
    // do something
}

$.ajax({
    ...
    success: function() { ... },
    error: handleAjaxError
});
ssilas777
  • 9,672
  • 4
  • 45
  • 68
Terry
  • 14,099
  • 9
  • 56
  • 84