sh03
sh032y ago

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
Nick
Nick2y ago
Error Formatting | tRPC
The error formatting in your router will be inferred all the way to your client (& React components)
sh03
sh03OP2y ago
@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?
Nick
Nick2y ago
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 formatter
sh03
sh03OP2y ago
So for any custom information I should use error.cause similarly?