Member-only story
Javascript — fetch API and HTML error statuses
Don’t get caught out by this somewhat surprising interaction.
I was writing a GET request to an endpoint the other day and in my testing, I was receiving a lot of 400 errors. 400 errors are to do with client errors, basically errors caused by the person making the request. Some common 400 errors are;
- 400 Bad Request
- 401 Unauthorized
- 404 Not Found
- 418 I’m a teapot (Ok maybe not so much this one, but it is a real error code)
Now, this was absolutely fine, I had excepted to run into these errors. But what I didn’t expect was that my API Hook (in my case React-query) was firing the onSuccess method when the API response came back. Basically, my call was failing with a 400 error but my API management hook thought it was succeeding. Very odd.
At first, I suspected foul play in React-query, that somehow 400 errors were coded as successes even though that seemed crazy to me.
But after some digging, I found that it was actually the ‘fault’ of the fetch API. And as it turns out, this is not a fault at all, this is expected behavior. So how does fetch handle HTTP error statuses?
What is Success?
To some of you reading, this article may seem extremely obvious — I think this comes down to our own definitions of success. To me, success in an API context means something like;
1. We sent our request
2. The server responded
3. We were authorized for that request
4. Our request is carried out
5. Everything works as it should, we get a 200's OK status 🥳
But this isn’t how fetch defines success. Fetch is only interested up to point 2. All that fetch cares about is if the network was able to carry out the request or not. Essentially, we can think of fetch working as such;
