最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - xmlHttpRequest.onerror handler use case - Stack Overflow

programmeradmin6浏览0评论

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 = '/';

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

From:

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

Share Improve this question asked Jul 12, 2017 at 21:35 DeveloperDeveloper 1,0223 gold badges17 silver badges34 bronze badges 1
  • 3 Possible duplicate of When should XMLHttpRequest's onerror handler fire – Cᴏʀʏ Commented Jul 12, 2017 at 21:39
Add a comment  | 

2 Answers 2

Reset to default 12

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?

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?

发布评论

评论列表(0)

  1. 暂无评论