zod
zod copied to clipboard
[superRefine] how to convert a ZodError to ctx.addIssue()
I have a schema where one of the properties (query) is too complex to validate to only use a zodSchema.
Yet, I made a parseQuery custom function that does the job and throw zodErrors as if it was a regular zodSchema.parse() execution.
here the implementation:
z.object({
name: z.string(),
query: z
.custom<Query>(v => v)
.superRefine((value, ctx) => {
try {
parseQuery(value);
} catch (error) {
if (error instanceof z.ZodError) {
error.issues.forEach(issue => { // this feels wrong
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: issue.message,
});
});
} else {
const message =
typeof error === 'object' &&
error !== null &&
'message' in error &&
typeof error.message === 'string'
? error.message
: 'Unknow query parsing error';
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: message,
});
}
}
}),
});
I have to iterate the initial error.issues produced by parseQuery and try to map them out to ctx.addIssue.
The example provided here does not map properly to many of the issues the parseQuery can have (many union errors).
I'm wondering, do we have a way to give the superRefine ctx, existing ZodErrors to get reported?
@nclsndr May I know what is the purpose of adding ctx.addIssue() ?
@tsdineshjai the ctx.addIssue method is meant to register custom errors, into the current zod state, encountered along the .superRefine execution.