Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try-catch doesn't work with XMLHTTPRequest

Tags:

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!

like image 814
chaohuang Avatar asked May 05 '12 03:05

chaohuang


2 Answers

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); 
like image 71
Joseph Avatar answered Sep 20 '22 18:09

Joseph


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.

like image 31
Mike Samuel Avatar answered Sep 20 '22 18:09

Mike Samuel