How to catch net::ERR_CONNECTION_REFUSED

ajax, exception, javascript, jquery

Solution

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.

Problem

Is there a way to catch `failed to load resource: net::ERR_CONNECTION_REFUSED`, I've tried: ``` try { $.post('',{},function(res) { }).fail(function (xhr, textStatus, errorThrown) { xhr.textStatus = textStatus; xhr.errorThrown = errorThrown; console.log('fail',xhr); // how to get the 'ERR_CONNECTION_REFUSED' or anything else as string? }); } catch(e) { console.log('catch',e); } ``` The fail function could catch, but I got no information about the error, either it is: - ERR_NAME_NOT_RESOLVED - ERR_CONNECTION_REFUSED - ERR_BLOCKED_BY_CLIENT - ERR_TUNNEL_CONNECTION_FAILED (when using proxy) or anything else.. the question would be, how to get the kind of error?

Original source