zod: Cannot get error message from safeParse
This should work:
//or process.env
const parsedEnv = envSchema.safeParse(Bun.env);
//@ts-ignore
if(parsedEnv.success === false) { console.error(parsedEnv.error.message); process.exit(1); }
but it doesn’t. Instead i have to do these shenanigans:
const parsedEnv = envSchema.safeParse(Bun.env);
if(parsedEnv.success === false) { console.error(JSON.parse(parsedEnv.error.message)[0].message); process.exit(1); }
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 24 (2 by maintainers)
@amany9000 There’s a quite easy workaround
So I believe this issue is still present and may have been misunderstood. I am not having any issues with the types, however the return type for
parsed.error.messageis wrong. It says I should receive a string, but I actually receive an array with one error object inside of it, like so:So, if you follow the documentation and provide
parsed.error.messageto the frontend, the frontend will show a JSON object. My current workaround is a function that grabs the error message and overrides the types like so:However, I don’t think this should be necessary. It would be nice if this was fixed at some point in the future! Thanks 😄
I’m seeing the same issue. Here’s my code where I’m seeing it. I changed the variable names for security reasons but, it doesn’t change anything.
VSCode Error for the underlined object:
It works if you do
result.success === false. But!result.successdoesn’t work…No it isn’t
You need to enable
strictNullChecks: trueorstrict: true. Once enabled you will not see this error. This is a requirement for Zod to properly type the results of parsing.This has nothing to do with strict mode.
when run
% node zod-repro.mjswith: zod@^3.22.4
The issue is resolved already?
Same, currenty facing this issue
@colinhacks @Creative-Difficulty, I’m facing the same issue and the return type for safeParse() is also incorrect.
Per today’s code I think the type is actually technically correct (the best kind of correct):
https://github.com/colinhacks/zod/blob/f7ad26147ba291cb3fb257545972a8e00e767470/src/ZodError.ts#L286-L288
i.e. the output of the
messagegetter is indeed a string, but a string of JSON rather than a human-readable message (as one might expect given the field’s name).I’ve opened #3937 to start a discussion about possible resolutions (starting with just a comment clarifying what the field actually returns).
I am still encountering this error. I have set
strict: truein mytsconfig.json.Tried
result.success === falseas a workaround solution but the build is still failing and returns an error message from safeParseSame here.
Workaround:
console.error((parsedObject as { error: Error }).error);This is still an issue
I have same problem,
