Search code examples
javascriptajaxxmlhttprequestonerror

xmlHttpRequest.onerror handler use case


What sort of situations could cause this handler to be called? I'm not finding any instance where this method throws an error.

I tried with the device offline, I get xmlHttpRequest.status = 0 but no error.

Question is what sort of situations can I create in order to test functionality of this handler.

var xmlhttp = new XMLHttpRequest(),
  method = 'GET',
  url = 'https://developer.mozilla.org/';

xmlhttp.open(method, url, true);
xmlhttp.onerror = function () {
  console.log("** An error occurred during the transaction");
};
xmlhttp.send();

From: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onerror


Solution

  • Your question is the perfect example. Just try your code from your web developer console while on this very page.

    enter image description here

    Here, try it yourself:

    var xmlhttp = new XMLHttpRequest(),
      method = 'GET',
      url = 'https://developer.mozilla.org/';
    
    xmlhttp.open(method, url, true);
    xmlhttp.onerror = function () {
      console.log("** An error occurred during the transaction");
    };
    xmlhttp.send();

    When dealing with any network based IO all kinds of things could happen. Cross-Origin requests are only one. What if the server is offline, DNS lookup fails, a router between you and the server that is critical point of failure goes down?