DEV Community

Cover image for Fetch API, do you really know how to handle errors?

Fetch API, do you really know how to handle errors?

Diona Rodrigues on November 29, 2023

The Fetch API is not that new and most developers have used it at some point to retrieve resources from a server, but do you really know how to han...
Collapse
 
georgehvm profile image
George Henrique

Amazing post!

I always tend to use fetch instead axios because it's native and with the knowledge acquired now it'll only just get better :)

Collapse
 
hilleer profile image
Daniel Hillmann • Edited

I usually question fellow colleagues why we should use fetch, native or not, over other (well-tested) libraries like axios where these examples provided in this post are provided out-of-the-box, rather than re-defining the same fetch util checks ourselves.

Collapse
 
appqui profile image
Igor Golodnitsky • Edited

(well-tested) libraries like axios

Always curious why send to browser 25 kb minified library, which does practically nothing. While we can use native code, which is doing the same, and cost nothing.

Collapse
 
dionarodrigues profile image
Diona Rodrigues • Edited

Thanks George!
Fetch API is very powerful and now it's also available in Node.js.

Collapse
 
cmgustin profile image
Chris Gustin

Great post! Simple and informative. I feel like I’ve had both of these methods (try/catch and response checking) explained in various courses and tutorials but this is the first time I’ve seen it all put together and explained clearly (or maybe it’s just the first time it’s clicked for my brain).

Collapse
 
dionarodrigues profile image
Diona Rodrigues

Happy to hear that @cmgustin !! :)

Collapse
 
ahangarha profile image
Mostafa Ahangarha

Why are you checking if (!response.ok) throw... again in the else block?

Collapse
 
dionarodrigues profile image
Diona Rodrigues • Edited

Hey, If you’re talking about the last code snippet (example 2), this is the explanation: after checking if the error is 404 or 500, we need a way to check any other kind of failed response, which can be done by using ‘!response.ok’. So, if the server returns 400, for example, this code will throw an error as well. For 404 and 500, we display customized messages, that’s the reason we use ‘response.status’ for them.

Please, let me know if I answered your question, otherwise I’d like you provide me with more detail about which example you are talking about.

Collapse
 
tudev profile image
Takashi Uemoto • Edited
if (response.ok) {...}
else { 
  if-
  // if(!response.ok) throw new Error(response.status) // redundant if-clause.
  throw new Error(response.status)
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
dionarodrigues profile image
Diona Rodrigues • Edited

I see what you both mean!
Code snippet updated. Thanks a lot for the review.

Collapse
 
michaeltharrington profile image
Michael Tharrington

This is an awesome post, Diona! Really nicely done. 🙌

Collapse
 
dionarodrigues profile image
Diona Rodrigues

Many thanks Michael!!! 🫶

Collapse
 
joxx profile image
joachim kliemann

Great article, thanks for posting

Collapse
 
dionarodrigues profile image
Diona Rodrigues

Thanks!!!!!

Collapse
 
stwissel profile image
Stephan H. Wissel

It gets really interesting when you get the more unusual response codes like 3xx or 1xx. Should you trust the automated redirect or look at the location header yourself?
In case of 1xx -> should you poll for results? The fetch API supports all this, so the ball is firmly in your application logic’s court

Collapse
 
kristjanesperanto profile image
Kristjan ESPERANTO

An ESLint rule for that would be nice 😃

Collapse
 
dionarodrigues profile image
Diona Rodrigues

That’s a nice idea!!!

Collapse
 
zhangzhengqiqi profile image
Aolef

Great post! The post make me learn more about fetch!

Collapse
 
kk_786 profile image
Kratarth

Great post!
I was using the Optimal way (mentioned in the last) to handle errors but was not entirely sure why its the optimal way. Now I know. Thanks a lot!

Collapse
 
dionarodrigues profile image
Diona Rodrigues

You are very welcome!!

Collapse
 
console_x profile image
F. Güngör

thanks for posting

Collapse
 
dionarodrigues profile image
Diona Rodrigues

You’re welcome! I hope you enjoyed it!! :)

Collapse
 
iwnow profile image
Vostroknutov Vitaliy • Edited

Nice! Need article about catch with AbortController :)

Collapse
 
ufukucar profile image
ufukucar

Very nice !

Collapse
 
shakilahmed007 profile image
Shakil Ahmed

Absolutely! Handling errors in the Fetch API is crucial for robust web applications. I'd love to learn more about your insights on best practices in error handling!

Collapse
 
dionarodrigues profile image
Diona Rodrigues

Thanks for the suggestion!!! :)

Collapse
 
umerfayyaz97 profile image
umerfayyaz97

Great Post.

Collapse
 
dionarodrigues profile image
Diona Rodrigues

Thank you!!!

Collapse
 
sakthivela0567 profile image
sakthi_l_u_c_i

Great article, thanks for posting

Collapse
 
dionarodrigues profile image
Diona Rodrigues

Thank you!

Collapse
 
dsaga profile image
Dusan Petkovic

Do you prefer using fetch or axios ? and how do you usually make fetch typesafe?

Collapse
 
dionarodrigues profile image
Diona Rodrigues

Hey @dsaga, of course axios provides some additional functionalities for handling HTTP requests, but most of the time I only need the native Fetch API.

Collapse
 
justaguyfrombr profile image
Misael Braga de Bitencourt

I rather use fetch, creating my own wrapper to fit the project needs.

Collapse
 
philipdeve profile image
Philip Ifeanyi

How about using Axios?

Collapse
 
dionarodrigues profile image
Diona Rodrigues

I would ask: why do you need to use Axios instead of the native Fetch API?

Collapse
 
hilleer profile image
Daniel Hillmann

Might not spend time building something that's already built

Collapse
 
console_x profile image
F. Güngör

may be not have time to get busy on json serialization

Collapse
 
foxeyerinx profile image
Rinx

Minor: should capitalize the i in the message initernal server error

if (response.status === 404) throw new Error('404, Not found');
if (response.status === 500) throw new Error('500, internal server error');
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lalami profile image
Info Comment hidden by post author - thread only accessible via permalink
Salah Eddine Lalami

check here advanced way to handle fetch error in react app : github.com/idurar/idurar-erp-crm/b...

IDURAR is open source erp crm based on mern-stack Node.js React.js MongoDB ANT Design : github.com/idurar/idurar-erp-crm

IDURAR  is open source erp crm based on mern-stack Node.js React.js MongoDB ANT Design

Collapse
 
amrit_anand_123 profile image
Amrit Anand

try {
const response = await fetch('restcountries.com/v4.1/all');

if (response.ok) {
console.log('Promise resolved and HTTP status is successful');
// ...do something with the response
} else {
// Custom message for failed HTTP codes
if (response.status === 404) throw new Error('404, Not found');
if (response.status === 500) throw new Error('500, internal server error');
// For any other server error
if (!response.ok) throw new Error(response.status);
}
}catch{
//This is executed when promises is not resolved.
}

Collapse
 
jeffchavez_dev profile image
Jeff Chavez

I need this. This is refreshing. I answered yes to your initial question. So I really need a review. Thank you.

Collapse
 
vincentbernet profile image
Vincent Bernet

Great post, very clear, nice to not need to use Axios anymore, a little util to wrap up this combination of try / catch with fetch and it looks good !

Collapse
 
emrekanbay profile image
EmreKanbay

Hmm, i always procrastiated about error handling and its incredible that you teached it so great. Doing something is hard, teaching is impossible

Some comments have been hidden by the post's author - find out more