try-catch doesn't work with XMLHTTPRequest

微笑、不失礼 提交于 2019-12-21 03:22:07

问题


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

When there was a 401 error thrown by xhr.sendMultipart, the error_handle_function was not called. Any idea how to fix this?

Thanks!


回答1:


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



回答2:


When there was a 401 error thrown by xhr.sendMultipart

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.

You need to register an onReadyStateChange handler and handle error responses there.



来源:https://stackoverflow.com/questions/10458632/try-catch-doesnt-work-with-xmlhttprequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!