0

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

1
  • Not sure why the use of the old XMLHttpRequest instead of await fetch() is so popular, and even less sure why forcing asynchronous things to be synchronous and blocking the UI is such a trend these days... Synchronous requests were never a thing. It's not really deprecated because it's never been "precated"(?) in the first place. Commented Apr 19, 2021 at 6:30

1 Answer 1

1

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();

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for the code sample. You use a asynchronous request, right? Does this mean reacting to the error is not possible with a synchronous_ request?
It's possible, but not recommended. See my update.
I tried your try ...catch solution, but the browser still quits the JS execution with a NS ERROR FAILURE and does not go through the catch part.
Which kind of browser did you use? I tested it in Edge and Chrome,where it worked fine.
Using Firefox 78.4.1esr. Maybe it is a Firefox issue or a version specific problem...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.