How to catch validation errors when using a zod schema in an endpoint
I prefer adding a Zod schema to the create endpoint body param when creating custom plugins with API routes.
It provides great DX, however, I cannot figure out how to catch validation errors.
I always receive “Invalid body parameters”.
From my understanding better-call throws APIError which causes better-auth to return a response.
I appreciate any guidance.
6 Replies
Yeah that's right.
If you need to handle the validation response then I would recommend setting the body to
z.any
or something like that to let the data go through, then in your endpoint handler code write your own validation logic with zod to handle the validation response.Good morning, @Ping
That's a real shame. The Zod schema in Better Call is a great feature; it's just missing support for errors.
Now BA is using Zodv4. We use the new toJSONSchema function to generate the OpenAPI schema, and we would lose this with z.any
Would you be open to a PR that lets users transform the error message in Better Call? Or maybe better a way to throw a validation error when using BA so it doesn't just return?
I'll see what I can do.
Legend 🙌, I will have a look too and share any updates here.
GitHub
update: Allow customizing validation error by ping-maxwell · Pull ...
This PR adds a onValidationError in the endpoint options to allow devs to intercept the validation error and throw their own custom error message if desired.
Omg you legend 🙌. I will take a look as soon as I get to my desk.