zomars
zomars2y ago

Zod Error Middleware

Hey lovely people. At Cal.com we make heavy use of zod for data validation. I was wondering if there's a way to create some kind of "error middleware" that can catch all Zod specific errors and serve the proper TRPC error back to the client. This would allow us to just use schema.parse instead of having to manually check schema.safeParse or having to use try/catch everywhere. Thanks for any input! 🙏
6 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
zomars
zomars2y ago
Not quite what I'm asking. Yeah I basically want to allow zod to fail anywhere (right now it just throws a 500). Catch that error en a middleware and respond a proper 400 with a better error message.
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
zomars
zomars2y ago
I don't think you can modify the error there
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Alex / KATT 🐱
Are you sure you want this? Do you ever use zod for stuff that isn't for validation? I feel like doing this might mask stuff that are actually internal errors Can you link me to a couple zod parsers within your codebase that you'd want to propagate as bad requests? Maybe there's another way of approaching But yes, this should be possible through the error formatter