Search code examples
javascriptxmlhttprequest

How to handle unreachable XMLHttpRequest endpoint


I have the following code which works as expected.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www......com', true);
xhr.responseType = 'json';
xhr.timeout = 2000;
xhr.onload = function() {
  if (xhr.response.success) {
   console.log(xhr.response.value);
  }
};
xhr.send();

Now, I'd like to handle when the third-party API is down and the endpoint is not reachable.

I have tried the following without success.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www......com', true);
xhr.responseType = 'json';
xhr.timeout = 2000;
xhr.onload = function() {
  if (xhr.response.success) {
   console.log(xhr.response.value);
  }
};
xhr.onerror = function() {
  console.log("There was an error");
};
xhr.send();

What am I missing?


Solution

  • You can't use try/catch to catch an asynchronous event.

    (Unless you are using Promises with async/await, which you are not).

    You need to use an error event handler

    xhr.onerror = function() {
        console.log("There was an error");
    };
    

    The modern equivalent would be:

    async function getJSON() {
       try {
           const response = await fetch(url);
           const data = await response.json();
           const status = response.status;
           return { status, data };
       } catch (error) {
           console.log(error);
       }
    }