Javascript 如何捕获涉及XmlHttpRequest的错误?

Javascript 如何捕获涉及XmlHttpRequest的错误?,javascript,ajax,Javascript,Ajax,当我通过XMLHttpRequest向服务器发送数据时,我希望借助TRY{}catch(){}捕获所有错误 我如何接收所有错误,例如net::ERR\u INTERNET\u DISCONNECTED等?请参考此 function createXMLHttpRequestObject() { // xmlHttp will store the reference to the XMLHttpRequest object var xmlHttp; // try to instantia

当我通过XMLHttpRequest向服务器发送数据时,我希望借助TRY{}catch(){}捕获所有错误

我如何接收所有错误,例如
net::ERR\u INTERNET\u DISCONNECTED
等?

请参考此

function createXMLHttpRequestObject()
{
  // xmlHttp will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // try to instantiate the native XMLHttpRequest object
  try
  {
    // create an XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
        try
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
    }
    catch(e) { }
  }
  // return the created object or display an error message
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

您应该将所有您认为会导致异常的语句放在try块中。之后,您可以给出几个catch语句——每个语句对应一个异常。在last中,您也可以给出finally-无论是否抛出或捕获异常,该语句都将在Try块之后执行

语法可以如下所示:

try{
try_statements
}

[catch (exception_var_2) { catch_statements_1 }]
[catch (exception_var_2) { catch_statements_2 }]
...
[catch (exception_var_2) { catch_statements_N }]

[finally { finally_statements }]
例如:

try {
   myroutine(); // may throw three exceptions
} catch (e if e instanceof TypeError) {
   // statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
   // statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
   // statements to handle EvalError exceptions
} catch (e) {
   // statements to handle any unspecified exceptions
   logMyErrors(e); // pass exception object to error handler
}

您可以在此处阅读更多内容:

尝试捕获对我不起作用。我个人最终测试了response==“”和status==0

        var req = new XMLHttpRequest();
        req.open("post", VALIDATE_URL, true);
        req.onreadystatechange = function receiveResponse() {

            if (this.readyState == 4) {
                if (this.status == 200) {
                    console.log("We got a response : " + this.response);
                } else if (!isValid(this.response) && this.status == 0) {
                    console.log("The computer appears to be offline.");
                }
            }
        };
        req.send(payload);
        req = null;

您是否使用jQuery或MooTools等javascript框架?如果不是的话,不妨考虑一下它们在Ajax功能中的成功/错误处理以及照顾跨浏览器问题等。不幸的是,我不喜欢任何框架。我想用纯JS)非常感谢。我是goonna试试看)这个try-catch公式是非标准的,而且只适用于mozilla(Firefox)。为什么还要检查
isValid()
?status==0是否已经表示客户端处于脱机状态?实际上,我似乎有一个问题,就是仅仅通过该检查无法捕获所有脱机状态。我不确定
status==0
在所有情况下是否足够,但请随意尝试;)我也可以想象,但是通过使用
&
可以将
状态==0
链接到其他条件。因此,您的代码说,“status==0就足够了,但我们还需要应用另一个条件”。这是我不明白的。在什么情况下,status==0不表示脱机?