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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:56:34  来源:igfitidea点击:

try-catch doesn't work with XMLHTTPRequest

javascriptxmlhttprequesttry-catch

提问by chaohuang

I am trying to use the try-catchstatements 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_functionwas not called. Any idea how to fix this?

当 抛出 401 错误时xhr.sendMultiparterror_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 truein your opencall means.

这意味着此代码在响应到达之前完成运行。这就是trueopen通话中的意思。

You need to register an onReadyStateChangehandler and handle error responses there.

您需要注册一个onReadyStateChange处理程序并在那里处理错误响应。