How to catch net::ERR_CONNECTION_REFUSED
Asked Answered
S

5

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?

Scottscotti answered 17/2, 2015 at 7:1 Comment(1)
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).Carboxylase
P
26

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.

Petit answered 17/2, 2015 at 7:1 Comment(6)
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.Strapped
Ok I got it. Thanks for mentioning @Claudio. Can you suggest any way to check rejection by network?Petit
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...Strapped
You should probably delete this answer since it does not answer the question.Discolor
@Discolor 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.Petit
I tried a lot to catch the above mentioned network errors, but it seems we have no luck yet but to wait for javascript to be able to handle such errors properly.Petit
P
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.

Poppo answered 26/5, 2017 at 7:11 Comment(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.Barina
P
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!")
  }
}
Patrinapatriot answered 31/1, 2023 at 10:49 Comment(0)
B
1

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);
}
xhttp.onreadystatechange
Basin answered 22/3 at 0:55 Comment(0)
C
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"

Catabasis answered 11/7, 2019 at 11:16 Comment(4)
How about browsers OTHER than Chrome - something that only works in one particular browser is less than 1/2 a answer.Trauma
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.Shannashannah
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-statusCepeda
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 !Adorno

© 2022 - 2024 — McMap. All rights reserved.