Is it possible to make Zod throw custom errors rather than a ZodError? #3280
-
I have a predefined error that occurs when there is a bad arg in an API call. Trying to move validation over to use zod. Could I instead make it so zod throws a custom error? export class BadApiArgumentException extends OttException {
name = "BadApiArgumentException";
arg: string;
reason: string;
constructor(arg: string, reason: string) {
super(`Bad argument: ${arg}: ${reason}`);
this.arg = arg;
this.reason = reason;
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
You can define custom error messages and act and/or do stuff based on that. const schema = z.string({
invalid_type_error: "This should be a string"
}); |
Beta Was this translation helpful? Give feedback.
-
Is this what you are looking for? class CustomException extends Error {
public name = 'CustomException'
constructor( public arg: string ) {
super( `Bad argument: ${ arg }` )
}
}
const result = z.string().safeParse( 123 )
if ( !result.success ) throw new CustomException( 'arg' ) If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
-
I think so! Thank you! |
Beta Was this translation helpful? Give feedback.
Is this what you are looking for?
If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏
https://github.com/sponsors/JacobWeisenburger