fetch: Reject promise with JSON error object

 // This does not work, since the Promise returned by `json()` is never fulfilled
return Promise.reject(resp.json());

Well, the resp.json promise will be fulfilled, only Promise.reject doesn’t wait for it and immediately rejects with a promise.

I’ll assume that you rather want to do the following:

fetch(url).then((resp) => {
  let json = resp.json(); // there's always a body
  if (resp.status >= 200 && resp.status < 300) {
    return json;
  } else {
    return json.then(Promise.reject.bind(Promise));
  }
})

(or, written explicitly)

    return json.then(err => {throw err;});

Leave a Comment