While working on the project, our developer encountered one feature of Prototype, which manifests itself in processing errors of Ajax requests:
Take a look at the following code (using Prototype 1.6.0.3):
var ajaxReq = new Ajax.Request ('Test.jsp', {
method: 'get',
onSuccess: function (transport) {
alert ('OK');
},
onFailure: function (transport) {
alert ('Failure');
}
});
It seems to be nowhere more banal, with a successful query, we get “OK”, and if the server spits out 404, 500 or something like that, then “Failure”. Everything is as it should be. However, guess how this code will behave if the server is unavailable (crashed, for example)?
In my case, if I nail Tomcat, then this code gives out ... “OK”! Immediately fair question - WTF?
')
A search on the Prototype docks gives the following:
Is the response a successful one?
The following is a list of guidelines for this kind of business.
For me personally, such guidelines appeared to be a small surprise. Viewing the HTTP spec showed that in general the status code should always be and its absence is not OK, but perhaps the Prototype developers decided on their own;) Ok, in one of their mailing lists I read that adding an exception handler catches this situation:
onException: function (requesterObj, exceptionObj) {
ajaxReq.options.onFailure (null);
}
However, when re-checking and it did not work ...
So, if this is news to you too, then I’m publishing the only right solution that catches all server problems:
var ajaxReq = new Ajax.Request ('Test.jsp', {
method: 'get',
onSuccess: function (transport) {
alert ('OK');
},
onFailure: function (transport) {
// this gets invoked if the server responds with an error code.
alert ('failure');
},
onException: function (requesterObj, exceptionObj) {
ajaxReq.options.onFailure (null);
},
on0: function (transport) {
// this gets invoked if the server is down.
ajaxReq.options.onFailure (transport);
}
});
The lack of a status code for XHR equals to the value 0, which leads to a callback in the
on0 () function, which must always be specified.