Promisifying XMLHttpRequest 时,如何捕获抛出错误

When Promisifying a XMLHttpRequest, how to catch a throw Error

在我承诺我的 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
  }
})();

我想捕获所有与网络相关的错误,此代码段已经做到了。现在,当我在 XHR 调用完成时链接我的 .then 调用时,我可以传递 Ajax 调用的结果。

这是我的问题:

当我在任何 .then 分支中抛出 Error 时,它不会被 catch 子句捕获。

我怎样才能做到这一点?

注意 throw new Error("throw error"); 不会被 catch 子句捕获....

完整代码见http://elgervanboxtel.nl/site/blog/xmlhttprequest-extended-with-promises

这是我的示例代码:

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);

});

问题是,错误是在 then 块被调用之前抛出的。

解决方案

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);
  });

提示

你为什么不使用 fetch()