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!
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);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.