How to catch net::ERR_CONNECTION_REFUSED

80,493

Solution 1

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.

Solution 2

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.

Share:
80,493
Kokizzu
Author by

Kokizzu

TechStacks (PL/DB only) C/C++ fan 2004.08-2012 Delphi fan 2005.08-2008.01 C# fan 2005.10-* PHP fan 2006.08-2009 Javascript fan 2009-2012, 2015.01-2021 PostgreSQL fan 2009-2019.06 Ruby fan 2012.08-2021.01 Go fan 2014.06-* Aerospike fan 2016.11-* Svelte fan 2020.03-* Tarantool fan 2020.09-* Clickhouse fan 2021.04-* TiDB fan 2021.11-* ScyllaDB fan 2022.03-* other preferred stack: SvelteNative, Unity3D Work History Lab and Teaching Assistant @ IE* Petra Christian University (2005-2008) Freelance Programming Tutor (2006-2014,2020) Network and System Administrator @ UPH Surabaya (2008-2010) Part-time Lecturer @ IE* Petra Christian University (2008-2011) Part-time Programmer and Teaching Assistant @ Information Systems UPH Surabaya (2010-2012) Lecturer @ IS* UPH Surabaya (2010-2013) Programmer @ Vi8e Interactive (2012-2013) Programmer and Lecturer @ IE* Surya University (2013-2014) Part-time Lecturer @ ICT* STKIP Surya (2013-2015) Freelance IT Consultant, IT Trainer (2014+) IT Specialist and Lecturer @ IS* President University (2014-2016) Backend Programmer @ Billions Platform (2016-2018) Game Programmer @ Alegrium (2018-2019) Backend Programmer @ Cyza (2020-2021) Backend Developer (Product) @ Bukalapak (2021-2021) Backend Developer (Platform) @ SoloFunds (2021-2022) Backend Developer (Product) @ secret (2022-now) IE* = Informatics Engineering IS* = Information Systems ICT* = Information and Communication Technology

Updated on July 05, 2022

Comments

  • Kokizzu
    Kokizzu almost 2 years

    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?

  • Claudio
    Claudio over 8 years
    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.
  • Kiran Shakya
    Kiran Shakya over 8 years
    Ok I got it. Thanks for mentioning @Claudio. Can you suggest any way to check rejection by network?
  • Claudio
    Claudio over 8 years
    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...
  • Zero3
    Zero3 about 8 years
    You should probably delete this answer since it does not answer the question.
  • Kiran Shakya
    Kiran Shakya about 8 years
    @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.
  • Kiran Shakya
    Kiran Shakya about 8 years
    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.
  • Shane
    Shane over 6 years
    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.
  • Paul Gorbas
    Paul Gorbas over 4 years
    How about browsers OTHER than Chrome - something that only works in one particular browser is less than 1/2 a answer.
  • Michael
    Michael over 4 years
    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.
  • Ray Foss
    Ray Foss over 3 years
    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