Type safe errors?

Hi, it's there a way to make something like this in Trpc?
import { useQuery } from "@tanstack/react-query"
import type { InferResponseType } from "hono"

import { honoClient } from "@/utils/hono"

const request = honoClient.api.hono.auth["get-session"].$post
type SuccessResponse = InferResponseType<typeof request, 200>
type ErrorResponse = InferResponseType<typeof request, 400>

export const useAuthSessionQuery = () => {
const query = useQuery<SuccessResponse, ErrorResponse>({
queryKey: ["useAuthSessionQuery"],
queryFn: async ({ signal }) => {
const response = await request({}, { init: { signal } })
if (response.status === 400) throw await response.json()
if (response.status === 500) throw new Error("Internal server error")
return await response.json()
},
})

return query
}
import { useQuery } from "@tanstack/react-query"
import type { InferResponseType } from "hono"

import { honoClient } from "@/utils/hono"

const request = honoClient.api.hono.auth["get-session"].$post
type SuccessResponse = InferResponseType<typeof request, 200>
type ErrorResponse = InferResponseType<typeof request, 400>

export const useAuthSessionQuery = () => {
const query = useQuery<SuccessResponse, ErrorResponse>({
queryKey: ["useAuthSessionQuery"],
queryFn: async ({ signal }) => {
const response = await request({}, { init: { signal } })
if (response.status === 400) throw await response.json()
if (response.status === 500) throw new Error("Internal server error")
return await response.json()
},
})

return query
}
The idea is to get also the query.error prop also type safe based on the output of the procedure
3 Replies
Nick
Nick2w ago
errorFormatter is what you want
Gary, el Pingüino Artefacto
Almost, but not quite there. For example, if a procedure requires some authentication, then in the error prop something like "AUTHENTICATION_ERROR", if the procedure also needs to validate permissions, then the error should be like "AUTHENTICATION_ERROR" | "MISSING_PERMISSIONS". With the errorFormatter, these errors will be on every procedure even if the procedure doesn't procedure them
Nick
Nick7d ago
Yes you should be throwing sensible errors that you can handle later The formatter just sets the shape / union of types.

Did you find this page helpful?