14

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

1

2 Answers 2

12

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?

4
  • 23
    onerror is only fired when an error occurs on the network level. Any HTTP codes, including 400 and over will not trigger onerror. Commented Feb 13, 2018 at 13:20
  • 1
    Just like Jonhan Gorter said, http response will not fire this event.
    – xi.lin
    Commented Sep 4, 2018 at 2:59
  • How to get a response? For instance I want to detect when fileuristrict is not turned on which won't allow a file read. How can I know there was an error? Commented Feb 26, 2020 at 7:16
  • There like is no HTTP error code if the server is offline, DNS lookup fails, or you can't route to the server. Commented Oct 8, 2020 at 21:25
1

Since an XHR call is for a server response, onerror would come into play when there is an error at the server. Changing your client to be offline doesn't simulate a server error.

Suppose the server resource gets moved and the server responds with a 404 error? What if the server times out? What if the request itself is malformed and causes the server to throw an error?

1

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.