Catch asynchronous network error from XMLHttpRequest send ()

I am making an http request using an XMLHttpRequest instance xhr

. I open it asynchronously:

xhr.open(
    method,
    uri,
    true
);

      

When I want to send something:

xhr.send(something)

      

It throws the following error when the server is down:

net::ERR_CONNECTION_REFUSED

      

How can I catch and handle this error when I make a request asynchronously? Standard

try {
} catch (err) {
}

      

does not work.

Thanks in advance.

+3


source to share


2 answers


use the onerror XMLHttpRequest () event:



 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 dumps to console
aGet("/", dmp) // ok, uses onload to trigger callback
aGet("http://dgfgdf.com/sdfsdf", dmp); //fails, uses onerror to trigger alert

      

+8


source


I wrote a complete solution to this problem and it works great I have a function called networkOrfail that will try every second to forward httprequest and only if the network is available in a different way, it ignores when it completes the request, it won't resend it again because it is it can be a very big problem, to make more than one request on the same landing page is a very big problem if all of these requests were successful, so let me help anyone who needs this method.

first detects when network is available or not with this function

function getNavigatorConection(){
  return navigator.onLine;
}

      

second create your HTTP request to be used below.

     function makeRequest(){

    let xhr = new XMLHttpRequest();
    xhr.open('GET', 'anypage/anotherpage', true);

    xhr.timeout = 2000;

    xhr.onload = function () {

    };

    if(xhr.readyState == 4 && xhr.status == 200){


    }

    xhr.ontimeout = function (e) {

    };

    xhr.send(null);

  }

      



Now listen to your request with this function function networkOrFail (callFunc, callTime) {

  let connected     =getNavigatorConection();
  let callableTimes =callTime < 2000 ? 2000 : callTime;
  let toursBegin    =3;
  let tours         =toursBegin;
  let intervalId;

  let request       = function(){

intervalId      = setInterval( function() { 

  let connected =getNavigatorConection();

  if(tours > 0){

    if(connected){

      callFunc();
      tours =0;
      return false;
    }
    tours--;
    alert("i tryied againt to resend for another time and it remain just "+tours+" to retry");
  }else{

    clearRequest();
    tours =toursBegin;
  }

}, callableTimes >5000 ? 5000 : callableTimes);

};

  let clearRequest  = function() {
  clearInterval(intervalId);
  intervalId    = null;
};

  if(connected){

   callFunc();

 }else{

    request();

 }

}

      

Call the listener like this

networkOrFail(makeRequest,5000);/*5000 is the number of minute you need to resend again the request in millisecon*/

      

Good luck.

+1


source







All Articles