Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
yusukebe opened this issue Feb 25, 2023 · 4 comments
Open

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

yusukebe opened this issue Feb 25, 2023 · 4 comments

Comments

@yusukebe
Copy link
Member

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
Copy link
Contributor

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
Copy link
Member Author

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
Copy link
Contributor

@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
Copy link
Member Author

yusukebe commented Nov 29, 2023

@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>
  }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants