Nacho Elias
Nacho Elias7mo ago

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,
},
}),
});
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" }),
});
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"
]
}
]
[
{
"validation": "uuid",
"code": "invalid_string",
"message": "Invalid Id",
"path": [
"id"
]
}
]
2 Replies
Alex / KATT 🐱
look up what .flatten() does maybe https://zod.dev/ERROR_HANDLING?id=flattening-errors
GitHub
TypeScript-first schema validation with static type inference
TypeScript-first schema validation with static type inference
Alex / KATT 🐱
I think you also get an err.data in the client or you did something off Not possible to help with the information provided, you probably have a setup error or two zods installed or something

Did you find this page helpful?