elbywan / wretch

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

Support for universal error catcher #192

Closed kibertoad closed 1 year ago

kibertoad commented 1 year ago

Currently it does not seem to be possible to specify one catcher for all errors, which may be preferable in case there is no logic specific to particular errors, but just one way to handle them all - e. g. passthrough to an external system, such as BugSnag or Sentry.

Would be great to have something like

wretch("...")
  .anyError((err) => console.log(err))
  .get()

It is sorta kinda doable via .get().res().catch() now, but this can only be applied per request, so it doesn't work as a system-wide (or a client-wide) hook.

elbywan commented 1 year ago

Hey @kibertoad,

Currently it does not seem to be possible to specify one catcher for all errors,

Thanks for your feedback! This is definitely a missing feature.

I just released v2.6.0 which implements a fallback catcher to handle this use case:

wretch(url)
  .catcher(404, err => redirect("/routes/notfound", err.message))
  .catcher(500, err => flashMessage("internal.server.error"))
  // this fallback will trigger for any error except if already caught by other means (like above for 404s and 505s)
  .catcherFallback(err => {
    log("Uncaught error:", err)
    throw err
  })

I hope this will suit your needs 🤞.

kibertoad commented 1 year ago

thanks a lot!

kuphg commented 1 year ago

Hey @elbywan I've actually quite needed this behaviour but found nothing about it on the README.md, it would be nice if it could be updated. Thanks.