elbywan / wretch

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

handling error before .[response type]() #45

Closed neves closed 5 years ago

neves commented 5 years ago

First of all, awesome API!

this works wretch().get().error() but not this wretch().error().get() gives .error is not a function.

How can I setup a default error handler, before calling get/post/etc?

elbywan commented 5 years ago

First of all, awesome API!

Hi @neves, thanks a lot 😄!

How can I setup a default error handler, before calling get/post/etc?

To do that, you can use the catcher method.

const w = wretch()
  .catcher(404, err => redirect("/routes/notfound", err.message))
  .catcher(500, err => flashMessage("internal.server.error"))

w.url(...).get() // 404 and 500 are already taken care of
neves commented 5 years ago

Is there a good reason I can't use .error and others syntactic sugar like .badRequest?

elbywan commented 5 years ago

Is there a good reason I can't use .error and others syntactic sugar like .badRequest?

Well these helpers (notFound, badRequest…) are meant to be used after the request resolves. catcher on the other hand is meant to be used before the request has been sent.

Using the helpers before the request has been sent will just not work and throw an error (the one you posted).

neves commented 5 years ago

Maybe the docs need to be updated at https://github.com/elbywan/wretch#catchers or even better, add those syntactic sugar to be used before request

elbywan commented 5 years ago

I find it confusing to duplicate method names (catcher is "borderline" already since it is used at 2 places). And I don't want to bloat the library by adding too much extra stuff.

Also, I already linked the proper section of the documentation in my previous comment:

https://github.com/elbywan/wretch#catchererrorid-number--string-catcher-error-wretchererror-originalrequest-wretcher--void

neves commented 5 years ago

Are you sure? This code does not work:

// Default catchers can be overridden if needed. w.url("...").notFound(err => / overrides the default 'redirect' catcher /)

elbywan commented 5 years ago

This code does not work

Indeed this line has a typo thanks for pointing this out 👍 (just pushed a fix).