DEV Community 👩‍💻👨‍💻

Pranjal Jately
Pranjal Jately

Posted on • Updated on

What the Fetch - Failed HTTP responses

So you think you know Fetch? Let's start with a little quiz...

Well done to those that guessed Okay.... If you didn't, don't feel bad, I too assumed that the code logs Error.... I then did some digging around and understood why it doesn't.

So, why does Fetch do this?

As per the docs on MDN{:target="_blank"},

A fetch() promise will reject with a TypeError when a network error is encountered or CORS is misconfigured on the server-side, although this usually means permission issues or similar — a 404 does not constitute a network error, for example.

(Or in our case a 500)

So, how do we handle this? The good news is, we can simply check if the Response.ok() property has a value of true.

{:target="_blank"}

So now the code logs Error: Internal Server Error, which is what you probably wanted in the first place.

Final Thoughts

Many of you, including myself, expected Error... to be logged from the very first snippet. This expectation probably comes from regularly using a library like Axios which handles the failed HTTP status code for you as seen in this CodeSandox{:target="_blank"}.

Let me know if you were caught out by this in the discussion section below. Ciao.

P.S. This is my first blog post so I would appreciate any feedback 😁

Top comments (0)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.