When Promisifying a XMLHttpRequest, how to catch a throw Error

2.7k views Asked by At

After I've Promisified my XMLHttpRequest, like so:

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.

Here is my question:

When I throw an Error in any .then branch, it will not get caught by the catch clause.

How can I achieve this?

Note that the throw new Error("throw error"); will not be caught in the catch clause....

For the entire code, see 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);

});
1

There are 1 answers

1
HaNdTriX On BEST ANSWER

The problem is, that the error gets thrown before your then block gets called.

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()?