How to create a unique method to handle errors with ajax

Asked

Viewed 878 times

9

I have a web application that performs several calls ajax. My college professor challenged me to create a generic message and combine the whole error treatment into a single function. Someone could 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')
    });
}
  • Basically, the task is to eliminate redundancies. Where there is repetition of codes, you must automate, leaving in a more generic way a single function that performs such processes since the parameters and the return are the same.

2 answers

6


You can use jQuery’s global ajax events, for example the .ajaxError(). Whenever an Ajax request is completed with an error, jQuery triggers the event .ajaxError() in it you can add your treatment as per 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;
    });
}
  • This is exactly what my teacher wanted, thank you very much

  • 1

    I’m glad it worked out! I’m available :))

2

The way @Brunno did, you would be setting an error that would be standard for all XHR requests on your page.

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

Behold:

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

Then just pass the name of the function as parameter fail

function getShoes() {

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

function getCoats() {

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.