elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.83k stars 98 forks source link

fetchError not being called #207

Closed hrishikesh-k closed 12 months ago

hrishikesh-k commented 12 months ago

Hey! Thanks so much for working on this project, it's a lifesaver!

Regarding the issue, I have referred to:

https://github.com/elbywan/wretch/issues/162 https://github.com/elbywan/wretch/issues/111 https://github.com/elbywan/wretch/issues/62

The goal is to catch any network error. So fetchError seems to be the correct way to do that. I have my code like:

const res = await wretch('https://www.example.com/404').get().fetchError(error => {
  console.log('error from fetchError')
}).text()

This throws a HTTP 404, so it should have been available in fetchError. But, it's not. It throws an uncaught exception. Based on this comment: https://github.com/elbywan/wretch/issues/111#issuecomment-877763857, this seems to be expected behaviour. So, I'm just supposed to move my fetchError to the end, except that doesn't work:

image

I get "Unresolved function or method fetchError()".

So, I tried to use catch() after my text(). But that breaks my response as my response now gets string | void type. I then have to check for the response everytime before processing. Furthermore, I don't get the status code as error.status if I use catch().

I'm sure I'm mixing up some concepts and confusing myself, but all I need is:

  1. Catch only network errors
  2. Capture the status code received from the server
  3. Keep my response type intact (not add a void type)

What am I missing?

elbywan commented 12 months ago

Hey @Hrishikesh-K,

Hey! Thanks so much for working on this project, it's a lifesaver!

Thanks a bunch! 🙇

What am I missing?

I think that what you are looking for is .catcherFallback().

.fetchError() is used to catch errors thrown by the fetch function itself, including "network errors" which are related to habing issues reaching the server (being offline for instance) - and they are unrelated to http codes.

The correct syntax would be:

wretch("https://jsonplaceholder.typicode.com")
  .catcherFallback((err) => console.log("http error", err.status))
  .get("/404")
  .fetchError((err) => console.log("network error", err))
  .json(console.log);
// => http error 404
hrishikesh-k commented 12 months ago

That was it, thanks!