jbaiter
jbaiter

Reputation: 7099

fetch: Reject promise with JSON error object

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 
HTTP/1.1 400 BAD REQUEST
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:

fetch(url)
  .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
   }

Upvotes: 70

Views: 72413

Answers (5)

Fdezdam
Fdezdam

Reputation: 23

Maybe this option can be valid

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

Upvotes: 0

insign
insign

Reputation: 5773

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;
  document.body.appendChild(image);
})
.catch(e => {
  console.log(e.message);
});

Upvotes: 0

user1902408
user1902408

Reputation:

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
myFetchWrapper(url)
  .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.

Upvotes: 13

Bergi
Bergi

Reputation: 664185

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

Upvotes: 104

Jeff Posnick
Jeff Posnick

Reputation: 56034

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.
myFetchWrapper('http://api.openweathermap.org/data/2.5/weather?q=Brooklyn,NY').then(console.log.bind(console));

// This should trigger the .catch() with the JSON response,
// since the response is an HTTP 400.
myFetchWrapper('https://content.googleapis.com/youtube/v3/search').catch(console.warn.bind(console));

Upvotes: 45

Related Questions