Thursday, August 21, 2008

Handle Error of createXMLHttpRequest

That's great if the browser knows a problem occurred, but sometimes the request will be lost forever. Thus, you usually want some kind of timeout mechanism as well. Using Event Scheduling, establish a timer to track the session. If the request takes too long, the timer will kick in and you can then handle the error. XMLHttpRequest has an abort() function which you should also invoke in a timeout situation. Here's a code example:

var xhReq = createXMLHttpRequest();
xhReq.open("get", "infiniteLoop.phtml", true); // Server stuck in a loop.
*** var requestTimer = setTimeout(function() {
xhReq.abort();
// Handle timeout situation, e.g. Retry or inform user.
}, MAXIMUM_WAITING_TIME); ***
xhReq.onreadystatechange = function() {
if (xhReq.readyState != 4) { return; }
** clearTimeout(requestTimer); **
if (xhReq.status != 200) {
// Handle error, e.g. Display error message on page
return;
}
var serverResponse = xhReq.responseText;
...
};

A timer has been introduced. The onreadystatechange() callback function will clear the timer once it receives the full response (even if that response happens to be erroneous). In the absence of this clearance, the timer will fire, and in this case, the setTimeout sequence stipulates that abort() will be called and some recovery action can then take place.

No comments:

Post a Comment