Việt An - How to get better error messages?I h...
How to get better error messages?
I have an union
z.union([z.literal('Conan'), z.literal('Jordan'), z.literal('Sona')])
, when the value is not any of that, the default error message I get is Invalid literal value, expected "Conan"
, but I want it to say something like ...expected "Conan", "Jordan" or "Sona"
. How can I do that?Solution:Jump to solution
Hmm, I actually don't know the answer off the top of my head.
z.union
is similar to z.object
or z.array
in that is a kind of "container" schema that runs the interior schemas and collects any errors.5 Replies
Solution
Hmm, I actually don't know the answer off the top of my head.
z.union
is similar to z.object
or z.array
in that is a kind of "container" schema that runs the interior schemas and collects any errors.In this specific instance (of literal strings) you might find
z.enum
easier to work with to get your desired outcome.
(You should actually get three errors for that particular union reporting the error reported by each schema.)I'm using
react-hook-form
, and the errors are extracted from that, so maybe it sees one error and forget the other two?
Anyway you're right, I'm using z.enum
and the message gets clearer
Invalid enum value. Expected 'Conan' | 'Jordan' | 'Sona', received 'Sonax'
Thanks a lotnp!
Unknown User•9mo ago
Message Not Public
Sign In & Join Server To View