How to create a single method to handle errors with ajax

9

I have a web app that runs several ajax calls . My faculty professor challenged me to create a generic message and unite the entire error handling in a single function. Can anybody help me ?

function getShoes() {

    $.get( "/Shoes/List", function( data ) {
        shoes = data;
    }).fail(function() {
        toastr.error('Erro ao buscar sapatos')
    });
}

function getCoats() {

    $.get( "/Coats/List", function( data ) {
        coats = data;
    }).fail(function() {
        toastr.error('Erro ao buscar casacos')
    });
}
    
asked by anonymous 04.09.2015 / 04:45

2 answers

6

You can use jQuery's global ajax events, for example .ajaxError() . Whenever an Ajax request is terminated with an error, jQuery triggers the event .ajaxError() in it you can add your treatment, according to the code below:

$( document ).ajaxError(function() {
     //sua menssagem de erro genérica
     toastr.error('Problemas ao buscar os dados!')
});

Implementation on top of your code:

/*executa após todo conteudo ser carregado*/
$( document ).ready(function() {
    /*adiciona o evento global no ready da sua pagina*/
    $( document ).ajaxError(function() {
         //sua menssagem de erro genérica
         toastr.error('Problemas ao buscar os dados!');
    });    
});

/*agora você pode editar suas funções retirando o evento do fail,
pois todos os erros serão tratados acima. Centralizando assim os erros*/
function getShoes() {

    $.get( "/Shoes/List", function( data ) {
        shoes = data;
    });
}

function getCoats() {

    $.get( "/Coats/List", function( data ) {
        coats = data;
    });
}
    
04.09.2015 / 05:01
2

In the way @Brunno did, you would be setting an error that would default to all XHR requests on your page.

Another way to do this is to declare a function that returns the error as a means of code reuse, and then call them as a parameter of fail .

See:

function ajaxError()
{
     console.log('Problemas ao buscar os dados!');
}

Then just pass the function name as a parameter of fail

function getShoes() {

    $.get( "/Shoes/List", function( data ) {
        shoes = data;
    });
    .fail(ajaxError);
}

function getCoats() {

    $.get( "/Coats/List", function( data ) {
        coats = data;
    })
    .fail(ajaxError);
}
    
04.09.2015 / 17:57