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();'POST', someurl, true);

When there was a 401 error thrown by xhr.sendMultipart, the error_handle_function was not called. Any idea how to fix this?


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)
        } else {
            error_handle_function(); //otherwise, some other code was returned
}'POST', someurl, true);

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