hono icon indicating copy to clipboard operation
hono copied to clipboard

Hono RPC Client: add option for response parsing

Open jansepke opened this issue 10 months ago • 1 comments

What is the feature you are proposing?

It would be great if the options of the hc() would allow to add a custom response parser to centralize common code that we want to be executed on every response, e.g.:

const client = hc<AppType>('', {
  handleResponse: async (res) => {
    if (!res.ok) throw Error("error")

   return await res.json()
  }
});

our current solution is to wrap every client call with a custom method that checks for errors and converts to json, e.g. parseResponse(await client.myEndpoint.$get())

Would it be feasible to implement this as it will likely complicate typing the client methods?

jansepke avatar Feb 06 '25 20:02 jansepke

If you just need the handling of !response.ok, then this is what I am doing:

const client = hc<AppType>('', {
  fetch: async (...args: Parameters<typeof fetch>) => {
    const response = await fetch(...args);
    if (!response.ok) throw new Error('Response not OK');
    return response;
  }
});

But there should be dedicated functionality for this so we can modify the response like you are doing and keep everything typesafe.

kylemclean avatar Feb 09 '25 09:02 kylemclean

Hey, i was keep copy pasting a little fetch proxy wrapper that i wrote across project for this exact use case, I finally take time to publish it, it's still in WIP but work well for those kind of use case you can take a look at https://github.com/Thomascogez/kool-fetch

Thomascogez avatar Jul 26 '25 00:07 Thomascogez

@jansepke @kylemclean good news, #4314 is accepted to be released in next minor, so if the needs is just error handling and parsing, just call parseResponse(client.hello.$get()) and you get a type-safe, automatically parsed result, with structured error in case the Response is not ok.

import { parseResponse, DetailedError } from 'hono/client'

const res = await parseResponse(client.hello.$get())
  .catch((e: DetailedError) => { console.error(e) }) // `parseResponse` will also automatically throw an error if the response is not `ok`.

NamesMT avatar Aug 01 '25 08:08 NamesMT

@NamesMT this looks great, thank you! I guess that it would be hard to integrate this into the hono client settings so we do not need to wrap all client invocations into parseResponse? (could be hard to type the client correctly I guess)

jansepke avatar Aug 08 '25 09:08 jansepke