25

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!

chaohuang
  • 3,965
  • 4
  • 27
  • 35

2 Answers2

38

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);
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • If you install [Web Server Notifier](https://chrome.google.com/webstore/detail/web-server-notifier/najdkmbedaehkepolllmpdfccdgooajh) on Chrome and try to go to play.google.com, for instance, you'll see a regular 404 error I can't prevent even checking status code before. Any idea on why? – cregox Jun 12 '13 at 21:30
  • On line 3, where does the xmlhttp object come from? – Phillip Senn Aug 07 '14 at 20:44
  • 3
    Chrome still throws error in console and then calls handler. – Hikmat G. Jun 10 '18 at 15:10
6

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.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245