Search code examples
javascripthtmlhttpxmlhttprequest

Catch asynchronous network error from XMLHttpRequest send()


I'm making an http request asynchronously using XMLHttpRequest:

xhr.open(method, uri, true);

When I send something:

xhr.send(something)

When the server is down, it throws the following error:

net::ERR_CONNECTION_REFUSED

How can I catch and handle this error? The standard try..catch block doesn't work as the request is asynchronous.

Thanks in advance.


Solution

  • Use the onerror event of the XMLHttpRequest:

    function aGet(url, cb) {
        var x = new XMLHttpRequest();
        x.onload = function(e) {
            cb(x.responseText)
        };
        x.onerror= function(e) {
            alert("Error fetching " + url);
        };
        x.open("GET", url, true);
        x.send();
    }
    
    var dmp = console.log.bind(console); // Dummy callback to dump to console
    aGet("/", dmp) // Ok, uses onload to trigger callback
    aGet("http://dgfgdf.com/sdfsdf", dmp); // Fails, uses onerror to trigger alert