Z
Zod12mo ago
Việt An

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:
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.
Jump to solution
5 Replies
Solution
Scott Trinh
Scott Trinh12mo ago
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.
Scott Trinh
Scott Trinh12mo ago
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.)
Việt An
Việt AnOP12mo ago
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 lot
Scott Trinh
Scott Trinh12mo ago
np!
Unknown User
Unknown User12mo ago
Message Not Public
Sign In & Join Server To View

Did you find this page helpful?