Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 762
Developer Avatar asked Jul 12 '17 21:07

Developer


People also ask

What is the purpose of XMLHttpRequest?

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.

How to call api using XMLHttpRequest?

To send an HTTP request, create an XMLHttpRequest object, open a URL, and send the request. After the transaction completes, the object will contain useful information such as the response body and the HTTP status of the result.

How do I fix XHR error?

How do I fix the XHR error? Technically, this is not error, it is normal response. The message tells you that you just tried to enter a secure room without the key, your error is that you don't have the key/authorization to enter that room. The only solution is to get the key/credentials and include on the request.


2 Answers

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?

like image 192
Alexander Higgins Avatar answered Oct 12 '22 01:10

Alexander Higgins


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?

like image 40
Scott Marcus Avatar answered Oct 12 '22 01:10

Scott Marcus