How to manage custom errors (e.g. custom error codes) in tRPC?
What's the recommended way to add fields to a TRPCError? How do you make that typesafe also on the client (e.g. custom error code is a specific union type).
Thanks
4 Replies
You want this: https://trpc.io/docs/error-formatting
Error Formatting | tRPC
The error formatting in your router will be inferred all the way to your client (& React components)
@Nick Lucas Yeah I read that but it's not clear to me. I currently throw
TRPCError
directly but in the example it seems like it's wrapping a ZodError
in clause
(which is unknown
so not typesafe) and then using that in a formatter. Is that the flow?So it's up to you to detect and format whatever errors you like, obviously Zod is a popular library with tRPC so that makes for a good example, but the example essentially just extends the default shape so TRPCError would also be handled there
Whatever you return from errorFormatter will have its type inferred as the error type downstream, so you can define whatever you like really
The example does a
error.cause instanceof ZodError
check to overcome the unknown
type of the error, just a limitation of having a global formatterSo for any custom information I should use
error.cause
similarly?