DEV Community

José Pablo Ramírez Vargas
José Pablo Ramírez Vargas

Posted on

Throwing if fetch() returns response.ok === false?? Terrible!

Can anyone think of a good reason why the masses of Javascripters decided that the norm is to throw an error on non-OK HTTP responses?? Because I can't.

To me, this is a terrible practice, and everyone just seems hypnotized by it, like moths to the flame.

I hear you all, potential moths. 😄

Top comments (3)

Collapse
 
mistval profile image
Randall

I don't think this is a norm in the general case. But if you're expecting an okay response and you don't get one, it makes sense to throw an error. If you're expecting a non-okay response, then it doesn't make sense to throw an error.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Hello, thanks for dropping by.

Not sure I follow. Shouldn't we all expect at least one non-OK response in the majority of cases? Or maybe all cases? I mean, which API is only expected to return 200? For example, saving data typed by user is prone to errors. We should always expect 200/400 as a minimum, right? Also, if your API is microservices, you should also always expect 504 with a body that describes the reason for unavailability.

This is my line of thinking. This is why I don't understand what you say: I always should have in mind that the happy path is not the only path, right?

Also, look at ky or axios: They both throw on non-OK responses, regardless of me having in mind the possibilities. This is why I hate these packages.

Collapse
 
mistval profile image
Randall

It's often the case that a GET requests is only ever expected to respond with a 200 status.

Of course any request can return 5xx errors, but it's often not pragmatic to have your code "expect" that, in the sense of having specific handling built for it rather than using error (exception) handling. If you throw an error in that case (and the error may include the response from the service, so it can be logged, shown to the user, etc) then you can generically bubble that error (or any other) up to the user so they can can see an error message and try again later. Your logging service can pick up the error generically (including stack trace) and log it, report it to error reporting, etc, and it can get looked into (or muted, if that's the right call). With some tooling, this can be made to happen easily for any error the application throws. That's more cumbersome to achieve without using errors.

I agree with you on axios, that's actually the thing I like least about axios (though I'm aware you can change that with non-default configuration). With fetch, I can examine the status and other response characteristics, and make a conscious decision whether to treat it as an error or not.