zod icon indicating copy to clipboard operation
zod copied to clipboard

[superRefine] how to convert a ZodError to ctx.addIssue()

Open nclsndr opened this issue 11 months ago • 2 comments

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 avatar Mar 20 '24 10:03 nclsndr

@nclsndr May I know what is the purpose of adding ctx.addIssue() ?

tsdineshjai avatar May 03 '24 07:05 tsdineshjai

@tsdineshjai the ctx.addIssue method is meant to register custom errors, into the current zod state, encountered along the .superRefine execution.

nclsndr avatar May 03 '24 08:05 nclsndr