Sunday, May 12, 2024
34
rated 0 times [  36] [ 2]  / answers: 1 / hits: 26390  / 12 Years ago, sat, may 5, 2012, 12:00:00

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!


More From » xmlhttprequest

 Answers
53

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

[#85783] Thursday, May 3, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradley

Total Points: 555
Total Questions: 102
Total Answers: 99

Location: Tajikistan
Member since Fri, Nov 27, 2020
4 Years ago
;