Javascript 如何捕捉网络::ERR_CONNECTION_REFUSED

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28556398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:59:43  来源:igfitidea点击:

How to catch net::ERR_CONNECTION_REFUSED

javascriptjqueryajaxexception

提问by Kokizzu

Is there a way to catch failed to load resource: net::ERR_CONNECTION_REFUSED, I've tried:

有没有办法赶上failed to load resource: net::ERR_CONNECTION_REFUSED,我试过:

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:

fail 函数可以捕获,但我没有得到有关错误的信息,要么是:

  • ERR_NAME_NOT_RESOLVED
  • ERR_CONNECTION_REFUSED
  • ERR_BLOCKED_BY_CLIENT
  • ERR_TUNNEL_CONNECTION_FAILED (when using proxy)
  • ERR_NAME_NOT_RESOLVED
  • ERR_CONNECTION_REFUSED
  • ERR_BLOCKED_BY_CLIENT
  • ERR_TUNNEL_CONNECTION_FAILED(使用代理时)

or anything else.. the question would be, how to get the kind of error?

或其他任何东西......问题是,如何得到那种错误?

回答by Kiran Shakya

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

我什至尝试使用 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...catchstatement fails to catch anything, because none of the functions inside try block is throwing any exceptions. It seems XMLHttpRequestis running in background thread, so its runtime error in not being catchable.

上面的代码片段只给出了一般的错误处理,而我没有得到错误背后的确切原因。该try...catch语句无法捕获任何内容,因为 try 块中的任何函数都不会抛出任何异常。它似乎XMLHttpRequest在后台线程中运行,因此无法捕获其运行时错误。

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

由于 jQuery 是一个库,它实际上是一个 javascript,它的行为也相同,$.post()因为$.post()也在XMLHttpRequest幕后使用。

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

下面是 jQuery 版本,它也将处理一般错误,因为我们无法确切知道错误的原因。

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

由于javascriptXMLHttpRequest()对于处理不同的错误状态仍然不够有效,我们无法知道AJAX请求网络错误背后的确切原因。我们只能捕获一般错误和一些其他已知的状态代码,例如

"404" for file not found

"500" for server not responding

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

找不到文件的“404”

“500”表示服务器没有响应

更多可以从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.onerrorcallback function for catching some generic errors but if you are still working with IE, then maybe it won't work.

更新:距离我上次更新这篇文章已经很长时间了。我看到的答案很少,试图实现类似的目标,但仍然收效甚微。正如该线程中的一些答案中提到的,我们还可以使用XMLHttpRequest.onerror回调函数来捕获一些通用错误,但如果您仍在使用 IE,那么它可能无法工作。

回答by Daniel Vest?l

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.

获取错误的另一种可能在以后更容易理解的方法是 onerror 事件处理程序。从我所看到的,它不会给你比 Kirans 解决方案更有用的信息。

回答by Ariel Garcia

You have access to online/offline in chrome.

您可以在 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"

在调用ajax之前,检查“ _Network_state