xmlHttpRequest.onerror handler use case

让人想犯罪 __ 提交于 2019-12-10 13:53:45

问题


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:


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

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?




回答2:


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?



来源:https://stackoverflow.com/questions/45067892/xmlhttprequest-onerror-handler-use-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!