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 😁

Oldest comments (0)