Nacho EliasN
tRPC2y ago
4 replies
Nacho Elias

Zod formatting Error

I'm using Zod for validation and whenever I get a validation error I'd like to be able to get the error message properly formatted. In the docs there's a section for this where it's sepcified that we can use the errorFormatter to achieve this. However, it's not doing anything at all. Btw, if I add a console.log within the errorFormatter nothing's being shown in the console, which is kind of weird if you ask me. However superjson is working completely fine, so I dont think its a configuration problem....

Here's my code

const t = initTRPC.context<typeof createTRPCContext>().create({
  transformer: superjson,
  errorFormatter: ({ shape, error }) => ({
    ...shape,
    data: {
      ...shape.data,
      zodError: error.cause instanceof ZodError ? error.cause.flatten() : null,
    },
  }),
});


This is my validation
export const GetProfileSchema = z.object({
  id: z.string().uuid({ message: "Invalid Id" }),
});


And this is what I get in my client in error.message instead of "Invalid ID"
[
  {
    "validation": "uuid",
    "code": "invalid_string",
    "message": "Invalid Id",
    "path": [
      "id"
    ]
  }
]
Was this page helpful?