How to detect DNS lookup error in JavaScript

How to detect DNS lookup error in JavaScript
How to detect DNS lookup error in JavaScript

In JavaScript, you can use the XMLHttpRequest object or the fetch() function to send an HTTP or HTTPS request to a server, and handle the response. However, these methods do not provide a way to detect DNS lookup errors directly.

One way to detect a DNS lookup error is to check the status code of the response, which should be 0 if the request failed due to a DNS error. Additionally, you can check the statusText property, which will be “DNS Lookup Failed” if a DNS error occurred.

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com", true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        if(xhr.status === 0 && xhr.statusText === "DNS Lookup Failed") {
            console.log("DNS Lookup Failed");
        } else {
            console.log("Request successful");
        }
    }
};
xhr.send();

Another way is to use fetch method.

fetch("http://example.com")
  .then(response => {
    if(!response.ok) {
      console.log("DNS Lookup Failed");
    }else {
      console.log("Request successful")
    }
  })
  .catch(error => console.log(error));

It is also important to note that different browser may have different way of handling this. In some cases browser may even not return anything, in such case you can set timeout to detect such failures.

Leave a Reply