views:

40

answers:

1

Let's suppose, for an example, that I want to partly clone Gmail's interface with jQuery Ajax and implement periodic auto-saving as well as sending. And in particular, let us suppose that I care about error handling, expecting network and other errors, and instead of just being optimistic I want sensible handling of different errors.

If I use the "low-level" feature of $.ajax() then it's clear how to specify an error callback, but the convenience methods of $.get(), $.post(), and .load() do not allow an error callback to be specified.

What are the best practices for pessimistic error handling? Is it by registering a .ajaxError() with certain wrapped sets, or an introspection-style global error handler in $.ajaxSetup()? What would the relevant portions of code look like to initiate an autosave so that a "could not autosave" type warning is displayed if an attempted autosave fails, and perhaps a message that is customized to the type of error?

Thanks,

+2  A: 

The common practice is to use $.ajaxSetup to specify a generic callback handler for errors during the non-$.ajax functions. E.g.

function init() {
    $.ajaxSetup({
        error: handleXhrError
    });
}

function handleXhrError(xhr, errorType, exceptionThrown) {
    // ...
}

Inside the handleXhrError you can display either a modal window or some notification bar like Gmail does, or replace the entire document, depending on the functional requirements. You can take action based on the response body as obtained by xhr.responseText and/or the HTTP status code from xhr.status. The values of the response body and status are controllable from the server side on. Those should provide enough information about the problem and which error action to take. The errorType will equal to 'timeout' when a timeout has occurred (i.e. network problem).

BalusC