If you are using jQuery’s AJAX you can use the .ajaxError() which is an event receiver. When you add it to document
it records in practice all the errors on that page. An example would be:
$(document).ajaxError(function(event, jqxhr, settings, thrownError) {
$( ".log" ).text( "Houve um erro no ajax!." );
});
There is still a possibility in jQuery, using the .ajaxSetup()
but jQuery himself advises against and says that it is better to use the method I put on top.
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('&');
You can expand this idea and make up a class with the methods of the class. So you can save more information and return this info in the error. But I think the example above answers your question.
You can use the same logic for other events, such as suggested on MDN:
xhr.addEventListener("progress", updateProgress, false);
xhr.addEventListener("load", transferComplete, false);
xhr.addEventListener("error", transferFailed, false);
xhr.addEventListener("abort", transferCanceled, false);
Thank you! Sanou until my future doubt was whether I could expand this form to other types of event..
– Vinícius Lara