2014-11-05 67 views
4

當我通過XMLHttpRequest發送數據到服務器時,我想在TRY {} CATCH(){}的幫助下捕獲所有錯誤。如何捕獲涉及XmlHttpRequest的錯誤?

如何接收所有錯誤,例如net::ERR_INTERNET_DISCONNECTED等?

+1

您是否使用任何JavaScript框架,如jQuery或MooTools?如果沒有,也許可以考慮,因爲他們在AJAX功能中內置了成功/錯誤處理功能,並且可以處理跨瀏覽器問題等。 – WizzHead 2014-11-05 12:08:01

+1

不幸的是,我不喜歡任何框架。我想用純JS) – 2014-11-05 12:17:13

回答

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

非常感謝。我要去試試) – 2014-11-05 12:14:58

-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

+0

非常感謝。我會嘗試一下代碼。 – 2014-11-05 12:16:01

+0

這個try catch配方是非標準的,只有mozilla(Firefox)。 – 2017-07-14 13:37:13

2

嘗試捕獲並沒有爲我工作。我個人最終測試了響應==「」和狀態== 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 go 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;