If you don't want Zod to throw errors when validation fails, use .safeParse. This method returns an object containing either the successfully parsed data or a ZodError instance containing detailed information about the validation problems.
This works fine and well so long as you stick to built-in refinements and schemas. But, if you make your own transformations/refinements, and they throw, then safeparse will throw.
I understand that user-defined .transform() and .refine() functions are not intended to throw, so they constitute an invalid schema. However, I would expect that to be reported from .safeParse() in a non-throwing way, for example
throwingSchema.safeParse("please don't throw!"); // { valid: false, code: 'INVALID_SCHEMA', message: 'Exception was thrown during user-defined `.transform()` callback' }
If we really want a method called "safeX" to throw, I would expect it to come in the form of an opt-in option, such as
From the docs,
This works fine and well so long as you stick to built-in refinements and schemas. But, if you make your own transformations/refinements, and they throw, then safeparse will throw.
I understand that user-defined
.transform()
and.refine()
functions are not intended to throw, so they constitute an invalid schema. However, I would expect that to be reported from.safeParse()
in a non-throwing way, for exampleIf we really want a method called "safeX" to throw, I would expect it to come in the form of an opt-in option, such as
Otherwise, we're stuck with
which defeats the purpose of
safeParse
in the first place.