So you think you know Fetch? Let's start with a little quiz...
Pranjal Jately 👨🏽💻@pjately🏆 #JavaScript quiz
What will the code below log to the console?
URL in snippet: httpstat.us/500
#100DaysOfCode #webdev #CodeNewbie #React12:35 PM - 21 Jun 2020
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 aTypeError
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.
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)