如何捕获net :: ERR_CONNECTION_REFUSED

Kok*_*zzu 47 javascript ajax jquery exception

有没有办法抓住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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Kir*_*kya 15

我甚至尝试使用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);
}
Run Code Online (Sandbox Code Playgroud)

上面的代码段只提供了一般的错误处理,而我没有得到错误背后的确切原因.该try...catch语句无法捕获任何内容,因为try块中的所有函数都没有抛出任何异常.它似乎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);
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

结论

由于javascript XMLHttpRequest()仍然不足以处理不同的错误状态,我们无法确定AJAX请求的网络错误背后的确切原因.我们只能捕获一般错误和一些其他已知的状态代码

"404"找不到文件

"500"表示服务器无响应

更多信息可以从https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html获知

  • 你应该删除这个答案,因为它没有回答这个问题. (3认同)
  • 我很确定state()与网络无关,而是与Deferred对象无关."被拒绝"意味着已拒绝延迟对象而不是已解决. (2认同)

Dan*_*tøl 5

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();
Run Code Online (Sandbox Code Playgroud)

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