如何捕获涉及XmlHttpRequest的错误?

时间:2014-11-05 12:02:50

标签: javascript ajax

当我通过XMLHttpRequest将数据发送到服务器时,我希望在TRY {} CATCH(){}的帮助下捕获所有错误。

如何收到所有错误,例如net::ERR_INTERNET_DISCONNECTED等?

3 个答案:

答案 0 :(得分:3)

尝试捕获对我不起作用。我个人最终测试了响应==“”和状态== 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;

答案 1 :(得分:0)

参考,

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;
}

答案 2 :(得分:-1)

您应该在try块中放置您认为会导致异常的所有语句。之后,您可以提供多个catch语句 - 每个语句都有一个例外。最后你也可以最后给出 - 无论是否抛出或捕获异常,这个语句都会在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
}

您可以在此处阅读更多内容:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch