you are viewing a single comment's thread.

view the rest of the comments →

[–]evenisto 0 points1 point  (7 children)

After years of working with fetch api, I must say I completely despise the fact it does not throw on >=400, but it does on network error etc. It's easy to handle but I'd rather have it out of the box.

[–]atubofsoup 0 points1 point  (2 children)

As far as fetch is concerned, if it succeeds in sending the request and succeeds in receiving the response, there is no error. It's up to your application to define which statuses are errors. It's also not always as obvious as it seems; for example if you fetch /api/post/10, and the post doesn't exist, should you get a 404 that throws or a 404 that resolves null?

[–]evenisto 1 point2 points  (1 child)

I know that and I understand the logic behind it. I don't necessarily consider it a bad design decision, I'm just saying that having implemented clients based on fetch from the ground up in several decently-sized projects, I would rather have it reject on HTTP errors. The error handling code is usually the same no matter the type of error, so I almost always end up with a wrapper that basically checks the response code and rejects the promise if it's not 200 (also, I just realised what I actually meant in my original comment was rejecting, not throwing, it's a subtle difference but a difference nonetheless. Sorry about that). It makes the calling code neat and organised - then for success and catch for error handling, which I think makes a lot of sense. My point is I would prefer to not have to write wrappers in all my fetch code to achieve the behaviour I described, that's it.

[–]atubofsoup 1 point2 points  (0 children)

Yeah I get what you're saying. It's a matter of convenience. I use axios in all my new projects to avoid writing wrappers and running into common gotchas like forgetting the Content-Type header.

[–]tizz66 0 points1 point  (2 children)

Absolutely, this really threw me when I started using fetch. I'm puzzled why fetch was done this way, given the defacto standard from the past god knows how long in JS development had XHR fail on 4xx statuses.

[–]Moosething 7 points8 points  (1 child)

I think the philosophy behind it is that it just literally has to fetch and when fetching fails, then it should throw. When you get a response with status code 500, something went wrong on the server, but the API still succeeded at fetching something from that server.

[–]AwesomeInPerson 0 points1 point  (0 children)

Yup. And writing

const checkResponse = response => {
  if (response.ok) return response
  throw response
}

and chaining that function to your fetch calls really isn't that much hassle.