本文介紹了try-catch 不適用于 XMLHTTPRequest的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試使用 try-catch
語句來處理來自 XMLHTTPRequest
的錯誤,如下所示:
I am trying to use the try-catch
statements to handle the errors from XMLHTTPRequest
, like below:
var xhr = new XMLHttpRequest();
xhr.open('POST', someurl, true);
try{
xhr.sendMultipart(object);
}
catch(err){
error_handle_function();
}
當 xhr.sendMultipart
拋出 401 錯誤時,error_handle_function
未被調用.知道如何解決這個問題嗎?
When there was a 401 error thrown by xhr.sendMultipart
, the error_handle_function
was not called. Any idea how to fix this?
謝謝!
推薦答案
我認為您無法以這種方式捕獲服務器錯誤.你應該檢查狀態碼:
I think you can't catch server errors that way. you should be checking the status code instead:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function() {
if (xhr.readyState === 4){ //if complete
if(xhr.status === 200){ //check if "OK" (200)
//success
} else {
error_handle_function(); //otherwise, some other code was returned
}
}
}
xhr.open('POST', someurl, true);
xhr.sendMultipart(object);
這篇關于try-catch 不適用于 XMLHTTPRequest的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!