AJAX - The Complete Reference

(avery) #1

PART II


Chapter 6: Networking Considerations 237


In cases outside the 200 range, particularly 400 and 500 requests, you should try to
handle the error with a retry, inform the user of the problem, or somehow log the failure. In
the library, we identify a number of status codes that are of particular interest for retry:

_networkErrorStatus : new Array(0, 408, 504, 3507, 12002, 12007, 12029, 12030,
12031, 12152),

A retry is in order for timeout-related HTTP responses (408 or 504) or general network related
problems. Note that Opera sets the status to 0 on some network errors, and the 12XXX errors are
Internet Explorer’s various network status indications. The special 3507 code is set to indicate
that a browser, particularly Firefox, is having a network error. If the response code matches a
value in AjaxTCR.comm._networkErrorStatus, the retry code is invoked.

/* see if it is one of our retry statuses */
if (response.retries)
{
for (var i=0;i<AjaxTCR.comm._networkErrorStatus.length;i++)
{
if (status == AjaxTCR.comm._networkErrorStatus[i])
{
AjaxTCR.comm._retryRequest(response);
return;
}
}
}

To address those server errors that cannot be recovered from via a retry, the onFail callback
is invoked by the library.

if (status == 200)
{
/* success handling */
}
else
response.onFail(response, status + " " + response.xhr.statusText);

For even more granularity, it might be desirable to handle particular error codes differently.
The library supports status code focused callbacks similar to the Prototype (www.prototypejs
.org) library. These are settable with onXXX where XXX is the three-digit HTTP status code
you are interested in catching. For example, on404, on403, or on500 would catch the
corresponding numeric status values responses. If there is a callback set this way, note that
it will be called before the appropriate onSuccess or onFail callback if one is defined.

/* check to see if the user wants a specific callback for this request */
if (response["on" + status])
response["on" + status](response);

A sample options object that uses a number of the previously discussed conditions is
shown here:

var options = { method: "GET",
onSuccess : showSuccess,
Free download pdf