fetch: Reject promise with JSON error object

Posted on

fetch: Reject promise with JSON error object – Even if we have a good project plan and a logical concept, we will spend the majority of our time correcting errors abaout javascript and promise. Furthermore, our application can run without obvious errors with JavaScript, we must use various ways to ensure that everything is operating properly. In general, there are two types of errors that you’ll encounter while doing something wrong in code: Syntax Errors and Logic Errors. To make bug fixing easier, every JavaScript error is captured with a full stack trace and the specific line of source code marked. To assist you in resolving the JavaScript error, look at the discuss below to fix problem about fetch: Reject promise with JSON error object.

Problem :

I have an HTTP API that returns JSON data both on success and on failure.

An example failure would look like this:

~ ◆ http get http://localhost:5000/api/isbn/2266202022 
Content-Length: 171
Content-Type: application/json
Server: TornadoServer/4.0

    "message": "There was an issue with at least some of the supplied values.", 
    "payload": {
        "isbn": "Could not find match for ISBN."
    "type": "validation"

What I want to achieve in my JavaScript code is something like this:

  .then((resp) => {
     if (resp.status >= 200 && resp.status < 300) {
       return resp.json();
     } else {
       // This does not work, since the Promise returned by `json()` is never fulfilled
       return Promise.reject(resp.json());
   .catch((error) => {
     // Do something with the error object

Solution :

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

Here’s a somewhat cleaner approach that relies on response.ok and makes use of the underlying JSON data instead of the Promise returned by .json().

function myFetchWrapper(url) {
  return fetch(url).then(response => {
    return response.json().then(json => {
      return response.ok ? json : Promise.reject(json);

// This should trigger the .then() with the JSON response,
// since the response is an HTTP 200.

// This should trigger the .catch() with the JSON response,
// since the response is an HTTP 400.

The solution above from Jeff Posnick is my favourite way of doing it, but the nesting is pretty ugly.

With the newer async/await syntax we can do it in a more synchronous looking way, without the ugly nesting that can quickly become confusing.

async function myFetchWrapper(url) {
  const response = await fetch(url);
  const json = await response.json();
  return response.ok ? json : Promise.reject(json);

This works because, an async function always returns a promise and once we have the JSON we can then decide how to return it based on the response status (using response.ok).

You would error handle the same way as you would in Jeff’s answer, however you could also use try/catch, an error handling higher order function, or with some modification to prevent the promise rejecting you can use my favourite technique that ensures error handling is enforced as part of the developer experience.

const url = 'http://api.openweathermap.org/data/2.5/weather?q=Brooklyn,NY'

// Example with Promises
  .then((res) => ...)
  .catch((err) => ...);

// Example with try/catch (presuming wrapped in an async function)
try {
  const data = await myFetchWrapper(url);
} catch (err) {
  throw new Error(err.message);

Also worth reading MDN – Checking that the fetch was successful for why we have to do this, essentially a fetch request only rejects with network errors, getting a 404 is not a network error.

I found my solution at MDN:

function fetchAndDecode(url) {
  return fetch(url).then(response => {
    if(!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    } else {
      return response.blob();

let coffee = fetchAndDecode('coffee.jpg');
let tea = fetchAndDecode('tea.jpg');

Promise.any([coffee, tea]).then(value => {
  let objectURL = URL.createObjectURL(value);
  let image = document.createElement('img');
  image.src = objectURL;
.catch(e => {

Maybe this option can be valid

new Promise((resolve, reject) => { 
    .then(async (response) => {
        const data = await response.json();
        return { statusCode: response.status, body: data };
    .then((response) => {
        if (response.statusCode >= 200 && response.statusCode < 300) {
        } else {

Leave a Reply

Your email address will not be published. Required fields are marked *