78

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?

1
  • 3
    You won't get specific information about the error, by intent (because otherwise it may be abused to gain insight into the user's internal network, for instance).
    – robertklep
    Jul 22, 2015 at 10:17

4 Answers 4

24

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.

6
  • 2
    I am pretty sure that the state() has nothing to do with the network, but with the Deferred object. The "rejected" means that the deferred object has been rejected instead of resolved.
    – Claudio
    Jan 24, 2016 at 11:04
  • Ok I got it. Thanks for mentioning @Claudio. Can you suggest any way to check rejection by network? Jan 24, 2016 at 11:52
  • Nope :( I am struggling behind that problem too, and unfortunately there isn't a solution that I can think of. Maybe I will investigate websocket to see if the diagnosis of a network problem could be a bit more interesting...
    – Claudio
    Jan 24, 2016 at 12:31
  • 5
    You should probably delete this answer since it does not answer the question.
    – Zero3
    Feb 4, 2016 at 9:44
  • @Zero3 I am currently trying to modify the answer so that it can meet the question requirement. If I fail, then I may delete the answer. If you know any answer, you may post below. I will delete the answer as soon as I see one. Feb 4, 2016 at 9:55
8
var xhttp= new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log(xhttp);

xhttp.onerror = function(e){
    alert("Unknown Error Occured. Server response not received.");
};

xhttp.open("POST", "http://localhost:8080/data", true);
xhttp.send();

An alternative way of getting errors that might be easier to understand later is the onerror event handler. From what I have seen, it won't give you any more useful information than Kirans solution.

1
  • Thanks, at least it detects that an error occurred (unlike try-catch around .send which doensn't seem to catch). My only concern is browser support for this. If not available, how else would you detect a network level error apart from using timeouts? Might be worth checking how $.ajax detects it before failing the promise.
    – Shane
    Dec 4, 2017 at 5:07
1

These types of errors occur when there's no connection with the server (meaning the server is not running). I faced this error and by looking at it there's no message, so my solution is to catch all errors that do not have a message like so:

catch (err) {
  if(!err.data?.message) {
    console.log("Server error please try later!")
  }
}
0

You have access to online/offline in chrome.

var _Network_state = true;
    function updateIndicator() {
        // Show a different icon based on offline/online
        if (navigator.onLine) { // true|false
            // ... do other stuff
            _Network_state = true;
        } else {
            // ... do other stuff
            _Network_state = false;
        }
        console.info(_Network_state ? 'Online' : 'Offline');
    }
    // Update the online status icon based on connectivity
    window.addEventListener('online',  updateIndicator);
    window.addEventListener('offline', updateIndicator);
    updateIndicator();

Before call ajax, inspect "_Network_state"

4
  • 1
    How about browsers OTHER than Chrome - something that only works in one particular browser is less than 1/2 a answer. Aug 30, 2019 at 0:47
  • 4
    It's really less than 2% of an answer, 99 times out of 100 a net::ERR_CONNECTION_REFUSED error will only occur when the browser is ONLINE anyway, as it indicates that a TCP reset was received from the peer (usually implying a service is down). Some level of network access would be required for that as a rule.
    – Michael
    Feb 1, 2020 at 14:18
  • info on this feature... pretty well supported but often not enough to tell if the user can actually connect to all your servers caniuse.com/online-status
    – Ray Foss
    Dec 18, 2020 at 22:28
  • Don't use this answer or you will encourage using one browser over others witch will lead to collapse of norms … . Here is something: imagine a browser is beaning used by 99% of users , whatever updates that browser does becomes the new way of doing things . and if we encourage this , we will lose the opensource ideology and became controlled by ... a company ! Aug 11, 2022 at 12:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.