How to pick up errors in AJAX requests?

Asked

Viewed 626 times

0

I need to pick up errors in sending the request and treat them in the application, in summary form the function works this way.

https://jsfiddle.net/n1p4k9jb/

I didn’t put the same one that is in my application to simplify the problem resolution, the difference is that in my application it has callbacks for the requests.

It works perfectly when the request is completed, then I take the data and the application continues, but when any failure occurs, none of the Alerts I put to indicate that at least fell in the execution block is called.

Another error that I can not catch, is if the user loses the internet connection, it is possible to test in the browser itself, in case Chrome has an option to simulate that is disconnected, in the console is generating an error described as net::ERR_INTERNET_DISCONNECTED, but I haven’t fallen into any execution block that I can handle the problem.

How can I catch request errors in AJAX?

I don’t want to use Jquery or any other library.

  • Guy here worked perfectly, I put an invalid url and Alert showed up showing the failed message.

  • I couldn’t catch the error when it gives cross-Omain or disconnected problem. Could you test the condition of "disconnect" from the Internet? It can be using the developer tools in the browser itself, Chrome has an option to simulate that you’re not with internet, this is the main error that I can’t catch.

  • Um... fine, I’ll try here.

1 answer

1


Hello Renan already understood your mistake, It is the following, when you perform a request and is without internet, your request is interpreted as a request for another domain thus leading to this problem of CORS, to solve this just add the header that enables CORS of any domain, follow the code:

function send (method, url, data)
{      
    var xhr = new XMLHttpRequest();

    xhr.ontimeout = function()
    {
        alert('timeout');
    }

    xhr.onload = function() 
    {
        if (xhr.readyState === 4) 
        { 
            if (xhr.status === 200) 
            {
                alert('success');
            } 
            else 
            {
                alert('failed');
            }
        }
        else
        {
            alert('failed');
        }
    };

    try
    {
        xhr.timeout = 10000;
        xhr.setRequestHeader('Access-Control-Allow-Origin', '*') //Linha modificada.
        xhr.open(method, url, true);
        xhr.send(data);
    }
    catch(er)
    {
        alert('failed');
    }
}

send('POST', '/echo/jsonp/', null);
  • Thank you for the suggestion Leonardo, but unfortunately I cannot use this means for safety reasons. I needed the catch to catch the error generated by xhr.send(), so I could treat it in the application.

  • 1

    hm..., I’ll take a look at this..

Browser other questions tagged

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