HTTP Promise - Handling Errors
<p>I am trying to find a nice way of handling http responses that I consider an error. I am using <code>fetch</code> in React Native. Here is my code.</p>

<pre><code>loginRequest(url) {
  return fetch(url, {
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;'
    },
    ....
  })
  .then(response =&gt; {
    return this.processResponse(response);
  });
}
</code></pre>

<p>Then... </p>

<pre><code>  processResponse(response) {
    if (response.status === 200) {
      return response.json();
    } else {
      let error = new Error(response.status);
      error.response = response.json(); // This is the problem
      error.status = response.status;
      throw error;
    }
  },
</code></pre>

<p>And the above are called like this:</p>

<pre><code>    return ApiRequests.loginRequest(username, password)
      .then(json =&gt; {
        dispatch(Actions.loginSuccess(json, username, password));
      })
      .catch(error =&gt; {
        dispatch(Actions.loginFailure(error));
      });
  };
</code></pre>

<p>The idea is that I can easily handle all the errors separately (we assume anything but 200 error), within the catch. The problem is that response.json() returns a promise, so assigning it to error.response is not working. I need to keep track of http status code and the response body.</p>