Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Follow publication

Member-only story

Javascript — fetch API and HTML error statuses

James Brightman
Dev Genius
Published in
4 min readDec 14, 2020

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;

A simplification of the fetch API success response

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Written by James Brightman

I write about stuff I find interesting. Usually WebDev, React and occasionally Finance.

No responses yet

Write a response