loading...
Cover image for Error Handling With Fetch

Error Handling With Fetch

connoro7 profile image Connor Dillon ・1 min read

Error handling with fetch is a bit different than with something like Axios or jQuery. If there is an http error, it will not fire off .catch automatically. You have to check the response and throw an error yourself. Here is an example:

fetch('https://jsonplaceholder.typicode.com/todo/1')
  .then(res => res.json())
  .then(res => {
    if (!res.ok) {
       throw new Error(res.error);
    }
    return res;
  })
  .catch(err => console.log(err));

I would suggest creating a separate function for error handling:

function handleErrors(res) {
  if (!res.ok) throw new Error(res.error);
  return res;
}

fetch('https://jsonplaceholder.typicode.com/todo/1')
  .then(res => res.json())
  .then(handleErrors)
  .then(res => console.log(res.data))
  .catch(err => console.log(err));

Discussion

pic
Editor guide
Collapse
savagepixie profile image
SavagePixie

A question worth asking is if a response other than 2xx or 3xx should be treated as an error. I'm not saying it shouldn't, but I don't think that should be the default either. Depending on what the call might return, you could have different handlers for what to do depending on the data you receive (array of objects vs empty response, for instance), and leave the catch to handle only network errors.

Again, I'm not saying this is the way to go, just saying that a 400 isn't always worth throwing an error.