Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap jQuery's $.ajax() method to define global error handling

Tags:

Branching off of questions like this one, I'm looking to wrap jQuery's $.ajax() method such that I can provide error handling in one location, which would then be used automatically by all of an application's remote calls.

The simple approach would be to simply create a new name, similar to how $.get() and $.post() implement facades to $.ajax(). However, I'm hoping to reuse the name $.ajax(), such that we can keep the rest of our code using the standard jQuery syntax, hiding from it the fact that we've added our own error handling. Is this practical and/or good to achieve, or possibly a horrible idea?

EDIT: The responses so far indicate .ajaxError() is the way to go. I know this will catch 400 and 500 level errors, but is there a way (with this event handler or otherwise) to catch 302 redirects as well? I'm trying to handle responses that are redirecting to a login page, but we want to intercept that redirect when it's an XHR request, allowing the user to cancel the action instead of forcing them forwards automatically.

like image 588
Marc L Avatar asked Dec 03 '10 02:12

Marc L


People also ask

How can we handle exception handling in Ajax?

This method is called when an HTTP request is successful. This method is called when an HTTP request fails. This method is called always, be the HTTP request fails or is successful. Example: We are going to see how to use AJAX fail() methods to handle the error in the HTTP requests.

How does error handle response in Ajax?

When there is an AJAX error response or the AJAX request times out, you'll want to log as much information as you have, including the error message that jQuery gives you, the url and the request data. $. ajax(url, { "data": requestData, "type": "POST", "timeout": 5000 }) .

What is processData in Ajax?

ProcessData = true : convert an object's name value pairs into a URL encoding, or an array's objects into name value pairs, or take a string as a literal.


1 Answers

You might want to look at $.ajaxError.

$(document).ajaxError(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {   alert("There was an ajax error!"); }); 

jQuery provides a whole bunch of other ways to attach global handlers.

To answer your edit, you can catch successful ajax requests with $.ajaxSuccess, and you can catch all (successful and failed) with $.ajaxComplete. You can obtain the response code from the xhr parameter, like

$(document).ajaxComplete(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {   alert("Ajax request completed with response code " + xhr.status); }); 
like image 179
sje397 Avatar answered Oct 03 '22 19:10

sje397