javascript try-catch 不适用于 XMLHTTPRequest
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10458632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
try-catch doesn't work with XMLHTTPRequest
提问by chaohuang
I am trying to use the try-catch
statements to handle the errors from XMLHTTPRequest
, like below:
我正在尝试使用try-catch
语句来处理来自 的错误XMLHTTPRequest
,如下所示:
var xhr = new XMLHttpRequest();
xhr.open('POST', someurl, true);
try{
xhr.sendMultipart(object);
}
catch(err){
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?
当 抛出 401 错误时xhr.sendMultipart
,error_handle_function
不会调用 。知道如何解决这个问题吗?
Thanks!
谢谢!
回答by Joseph
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);
回答by Mike Samuel
When there was a 401 error thrown by xhr.sendMultipart
当 xhr.sendMultipart 抛出 401 错误时
It was not thrown. It was returned asynchronously.
它没有被抛出。它是异步返回的。
That means that this code finishes running before the response arrives. That's what the true
in your open
call means.
这意味着此代码在响应到达之前完成运行。这就是true
您open
通话中的意思。
You need to register an onReadyStateChange
handler and handle error responses there.
您需要注册一个onReadyStateChange
处理程序并在那里处理错误响应。