简体   繁体   English

承诺XMLHttpRequest时,如何捕获引发错误

[英]When Promisifying a XMLHttpRequest, how to catch a throw Error

After I've Promisified my XMLHttpRequest, like so: 承诺了XMLHttpRequest之后,如下所示:

var Request = (function() {
var get = function(url){
    return request('GET', url);
  },
  post = function(url){
    return request('POST', url);
  },
  request = function(method, url) {
    return new Promise(function (resolve, reject) {
      var xhr = new XMLHttpRequest();
      xhr.open(method, url);
      xhr.onload = function(e){
        if (xhr.status === 200) {
          resolve(xhr);
        } else {
          reject(Error('XMLHttpRequest failed; error code:' + xhr.statusText));
        }
      },
      xhr.onerror = reject;
      xhr.send();
    });
  };

  return {
    get: get,
    post: post,
    request: request
  }
})();

I'd like to catch all network related errors, which this snippet already does. 我想捕获所有与网络相关的错误,此代码段已经做到了。 Now, when I chain my .then calls when the XHR calls are finished, I can pass around the result of the Ajax call. 现在,当XHR调用结束时链接.then调用时,我可以传递Ajax调用的结果。

Here is my question: 这是我的问题:

When I throw an Error in any .then branch, it will not get caught by the catch clause. 当我在任何.then分支中引发Error.then catch子句不会捕获该Error

How can I achieve this? 我该如何实现?

Note that the throw new Error("throw error"); 注意, throw new Error("throw error"); will not be caught in the catch clause.... 不会在catch子句中被捕获。...

For the entire code, see http://elgervanboxtel.nl/site/blog/xmlhttprequest-extended-with-promises 有关整个代码,请参见http://elgervanboxtel.nl/site/blog/xmlhttprequest-extended-with-promises

Here is my example code: 这是我的示例代码:

Request.get( window.location.href ) // make a request to the current page
.then(function (e) {

 return e.response.length;

})
.then(function (responseLength) {

  // log response length
  console.info(responseLength);

  // throw an error
  throw new Error("throw error");

})
.catch(function(e) { // e.target will have the original XHR object

  console.log(e.type, "readystate:", e.target.readyState, e);

});

The problem is, that the error gets thrown before your then block gets called. 问题是,在您的then块被调用之前就抛出了错误。

Solution

Request
  .get('http://google.com')
  .catch(function(error) {
    console.error('XHR ERROR:', error);
  })
  .then(function(responseLength) {
    // log response length
    console.info(responseLength);
    // throw an error
    throw new Error("throw error");
  })
  .catch(function(error) { 
    // e.target will have the original XHR object
    console.error('SOME OTHER ERROR', error);
  });

Hint 暗示

Why are you not using fetch() ? 为什么不使用fetch()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM