try-catch doesn’t work with XMLHTTPRequest

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 answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Moment.js: Date between dates

Similar Posts