javascript - 如何捕捉网络::ERR_CONNECTION_REFUSED

标签 javascript jquery ajax exception

有没有办法捕获加载资源失败: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);
}

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

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

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

最佳答案

我什至尝试使用 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);
}

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

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

以下是 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>

结论

由于 javascript XMLHttpRequest() 在处理不同的错误状态方面仍然不够有效,我们无法知道 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

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

关于javascript - 如何捕捉网络::ERR_CONNECTION_REFUSED,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28556398/

相关文章:

javascript - 如何在XDR请求中指定dataType?

javascript - 从文本中删除所有 Unicode 破折号/连字符

javascript - php 中的 json_decoded 数组 - 获取键和值

javascript - Windows 10 32 位上的 Edge 阻止对本地主机的 ajax 调用,网络错误 0x2efd

javascript - Django Form - 使用 JQuery 条件字段显示

javascript - 带有授权 header 的 Ajax GET

javascript - 如何使弹出窗口在关闭后停留在同一区域

javascript - IE 不显示在 Javascript 中完成的更新的 IMG SRC 更改

javascript - jquery 显示超时倒计时输出

asp.net - Sys 未定义 - 仅 IE 7 中的 ajax 问题