Z4RM - Hello! I'm going to write a fullstack ap...
Hello! I'm going to write a fullstack application, and for types consistency between my backend and frontend, I'm looking at Zod and implementing it in my app.
However, I'm running into an issue: I want to include the
error
object returned from the parse
method, but I don't find how I can "include" it in a z.object
.
I'm not sure if what I say is very clear, so here is an explanation in code:
So, my question is: here is a way to do this, and if yes, how? Thank you by advance! 😄9 Replies
Solution
You could use z.custom for this
Okay, so I imagine I'm obliged to create by myself a validator.
Thanks in any case!
how do you mean?
I mean I guess you mean you want to parse the error but my question is why 😄
if you're not going to trust the error coming out of Zod why trust the parsing it's doing
No I mean like backend could send an
error
which is not a ZodFormattedError<Credentials>
In that case just type it as such, probably best using a discriminated union like
{code: "INPUT_PARSING" , error: z.ZodError...} | {code: "UNCAUGHT", error: unknown}
but also FYI if this is for typing a back end endpoint, you can't really serialise Errors (and shouldn't really try to either as they have info like the stack trace that shouldn't make it to the client)You mean
ZodFormattedError
contains stack trace?aah shit sorry completely misread that
no formatted error is fine!
No it's my fault, in my orginial message I write
SafeParseReturnType<Credentials>
yea that one would have a stack trace if I have it right