honojs / hono

Web framework built on Web Standards
https://hono.dev
MIT License
18.52k stars 522 forks source link

[Feature suggestion] "after" hook for Hono Client #928

Open yusukebe opened 1 year ago

yusukebe commented 1 year ago

From discord. About Hono Client.

Sometimes we want to write a common handling when receiving responses.

const res = await client.api.hello.$get()
if (res.status === 404) {
  window.location.href = '/'
}

// ...

const res = await client.api.morning.$get()
if (res.status === 404) {
  window.location.href = '/'
}

// ...

Since it is tedious to write the same process every time, how about having a hook for when the response is received?

const client = hc<AppType>('/api', {
  after: (res) => {
    if (res.status === 404) {
      window.location.href = '/'
      return
    }
  }
})

It can also be used to output logs, for example.

const client = hc<AppType>('/api', {
  after: (res) => {
    console.log(`Response status is ${res.status}`)
  }
})
MonsterDeveloper commented 10 months ago

Hi @yusukebe! Is there an ETA on this feature? Really want to implement a generic error handling method for all requests (or better said, responses).

I saw you even opened a PR, but closed it in September.

yusukebe commented 10 months ago

Hi @MonsterDeveloper

I closed that PR because we may have to implement hooks other than after, and that would complicate things. I do agree that hc() should be small. However, if there are enough requests and we can find a good way to implement it I'd like to do that.

MonsterDeveloper commented 10 months ago

@yusukebe what do you think about doing it similarly to axios' interceptors?

hc could have interceptors (or middleware) before the request is sent to modify the config sent to the fetch method. And interceptors for response that would be attached via .then, .catch, or .finally.

yusukebe commented 9 months ago

@MonsterDeveloper

It might not be perfect solution, but you can use a custom fetch which handles errors:

const client = hc<AppType>('http://localhost:3000', {
  fetch: async (req: Request, init?: RequestInit) => {
    return fetch(req, init)
      .then((res) => res)
      .catch((e) => {
        console.error('Custom error message:', e)
      }) as ReturnType<typeof fetch>
  }
})