If you are using jQuery AJAX you can use the .ajaxError () which is an event drop-in. When you add it to document
it actually registers all the errors that are on that page. An example would be:
$(document).ajaxError(function(event, jqxhr, settings, thrownError) {
$( ".log" ).text( "Houve um erro no ajax!." );
});
There's still a possibility in jQuery, using .ajaxSetup()
but jQuery itself advises against saying it's better use the method I put above.
Note : Global callback functions should be set with their respective global Ajax event handler methods
If you are using native AJAX you can use a constructor function like this:
function erroAjax(e) {
alert('Houve um erro no ajax!');
}
function novoXHR() {
var xhr = new XMLHttpRequest();
xhr.addEventListener("error", erroAjax, false);
return xhr;
}
var xhr1 = novoXHR(); // deve funcionar
var xhr2 = novoXHR(); // vai dar erro
xhr1.open('POST', '/echo/html/', true);
xhr1.send('foo=bar');
xhr2.open('POST', 'http://stackoverflow.com', true);
xhr2.send('&');
jsFiddle: link
You can expand this idea and even make a class of yours with the methods of the class. So you can save more information and return this info in error. But I think the example above answers your question.
You can use the same logic for other events, such as suggested in MDN a>:
xhr.addEventListener("progress", updateProgress, false);
xhr.addEventListener("load", transferComplete, false);
xhr.addEventListener("error", transferFailed, false);
xhr.addEventListener("abort", transferCanceled, false);