DEV Community

loading...
Cover image for Error Handling With Fetch

Error Handling With Fetch

Connor Dillon
Full-stack Javascript developer, fire dancer, physics nerd, Vim fanboy, and technical writer! I'm passionate about my work and love to talk shop, so say hi!
・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));
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

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.

Collapse
vercetti11 profile image
Octavio Vercetti

Check res.ok field in the frist then(). When you parse it with .json() you strip it out of the ok field.