How to catch net::ERR_CONNECTION_REFUSED

I even tried to achieve the goal using javascript XMLHttpRequest()

var xhttp= new XMLHttpRequest();
try{
  xhttp.onreadystatechange = function() {
    console.log(xhttp);
    if (xhttp.readyState == 4 && xhttp.status == 0) {
      alert("Unknown Error Occured. Server response not received.");
    }
  };
  xhttp.open("POST", "http://localhost:8080/data", true);
  xhttp.send();
}catch(e){
  console.log('catch', e);
}

Above snippet only gives generic error handling, while I am not getting exact reason behind the error. The try...catch statement fails to catch anything, because none of the functions inside try block is throwing any exceptions. It seems XMLHttpRequest is running in background thread, so its runtime error in not being catchable.

As jQuery is a library which is actually a javascript, it will also behave same for $.post() because $.post() is also using XMLHttpRequest behind the curtain.

Below is the jQuery version, which also will handle generic error, as we can not exactly know reason for error.

try {
  $.post('http://localhost:8080/data', {}, function(res) {}).fail(function() {
      alert("Unknown Error Occured. Server response not received.");
  });
} catch (e) {
  console.log('catch', e);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Conclusion

As javascript XMLHttpRequest() is still not efficient enough for handling different error states, we can not know exact reason behind the network error for AJAX requests. We can only capture generic errors and some other known status codes like

“404” for file not found

“500” for server not responding

More can be known from https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

Update:
It has been a very long time since I last updated this post. I saw few answers which try to achieve similar objectives but still with very little success. As mentioned in some of the answers in this thread we can also use XMLHttpRequest.onerror callback function for catching some generic errors but if you are still working with IE, then maybe it won’t work.

Leave a Comment