Improved jquery ajax error reporting

jQuery is a great library, and I highly recommend it after 6 months of use. One of the problems I’ve had with it, however, is its poor error reporting on ajax requests. While you can subscribe to the global event ajaxError, there’s nothing to tell you what went wrong. Specifically, I’ve wanted a way to report when the json parse fails.

Looking through the jQuery core, I found that the problem is that “status” field isn’t sent to the handler. A simple intervention on jQuery.handleError will close the gap:

jQuery.handleErrorOriginal = $.handleError;
jQuery.handleError = function( s, xhr, status, e ){
  if (s.global) {
    xhr.error_status = status;
  }
  jQuery.handleErrorOriginal.apply(this, arguments);
};

The “e” object is the original ajax configuration object. Since it reaches the global ajaxError listener, we can pull the status out of that.

Notice that I don’t replace the original functionality, I just do something before calling it with the same scope and arguments. The reason here is forwards-compatibility. Assuming that the name and api of jQuery.handleError doesn’t change, any changes to its internal functionality in future updates will likely be preserved without refactoring effort on your part.

To catch the errors:

$("html").ajaxError(function(xhr, s, e){
    var msg;
    switch (s.error_status) {
      case "parsererror":
        msg = "A JSON parsing error occurred.";
        break;
      case "timeout":
        msg = "An ajax request timed out.";
        break;
      default:
        msg = "An ajax error occurred.";
        break;
    }
    alert(msg + "\n\n" + e.url);
});

Why do I set xhr.error_status and then read s.error_status? Because, somewhere in the jumble of handleError and trigger, xhr becomes s. I love jQuery, but some of its core code can be quite difficult to read through.