Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX Error Handling (HTTP Status Codes)

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.

like image 244
FtDRbwLXw6 Avatar asked Oct 04 '12 19:10

FtDRbwLXw6


People also ask

How do you handle errors in AJAX call?

The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.

What are AJAX errors?

Many pages send AJAX requests to a server. Because this relies on the cooperation of the server and the network between the client and the server, you can expect these AJAX errors: Your JavaScript program receives an error response instead of data; Your program has to wait too long for the response.

How can make AJAX call in jQuery?

The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request. Parameters: The list of possible values are given below: type: It is used to specify the type of request. url: It is used to specify the URL to send the request to.


1 Answers

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 }); 
like image 97
Terry Avatar answered Sep 19 '22 12:09

Terry