Search code examples
javascriptexceptionxmlhttprequest

How to react to a NS ERROR FAILURE error in the browser's Javascript


In Firefox' JavaScript engine I do a (deprecated) synchronous XMLHttpRequest like this:

var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:8780/BoilerData/invention.html', false);
request.send();

if (request.status === 200) {
  ...
} else {
  ...
}

Problem is when the server myserver.com is not running I get in the browser console a NS ERROR FAILURE error and the else part is not executed.

However I would like to react to this error in JavaScript. How can I catch this error and react to it (e.g. with using another server) while still doing a a synchronous XMLHttpRequest.

Update

Here more details to the error message. In the console of my browser (Firefox 78.4.1esr) I see the following:

Error in Firefox


Solution

  • If you prefer a synchronous request, try catch the net::ERR_CONNECTION_TIMED_OUT exception:

    var request = new XMLHttpRequest();
    request.open('GET', 'http:/myserver.com/bar/foo.txt', false);
    try{
      request.send();
      if (request.status === 200) {
        //...
      }
    }catch(e){
      console.log('Got an exception: ', e);
      //else ...
    }

    Synchronous XMLHttpRequest on the main thread is deprecated, you may want to do request.open asynchronously, and put the else logic in onerror event processor:

    var request = new XMLHttpRequest();
    request.open('GET', 'http:/myserver.com/bar/foo.txt', true);
    
    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
        //    ...
        } 
    }
    request.onerror = function() {
       console.log('An error occured! status = ', request.status);
       // what else {
       // ...
    }
    
    request.send();