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 8 months ago
  • Comments: 17 (1 by maintainers)

Most upvoted comments

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.

const envSchema = z.object({
  NODE_ENV: z.string().default("development"),

  // FOO
  FOO_API_KEY: z.string(),

  // BAR
  BAR_KEY: z.string(),
  BAR_REGION: z.string(),
})

const parsed = envSchema.safeParse(process.env)

if (!parsed.success) {
  console.error(
    `Error #%d: Failed Parsing .env file.
    Please ensure that it exists and is valid: `,
    JSON.stringify(parsed.error.format(), null, 4)
    //                    ^^^^^
  );
  process.exit(1);
} else {
 ...
}

VSCode Error for the underlined object:

Property ‘error’ does not exist on type ‘SafeParseReturnType<{ NODE_ENV?: string; FOO_API_KEY?: string; BAR_KEY?: string; BAR_REGION?: string; }, { NODE_ENV?: string; FOO_API_KEY?: string; BAR_KEY?: string; BAR_REGION?: string; }>’. Property ‘error’ does not exist on type ‘SafeParseSuccess<{ NODE_ENV?: string; FOO_API_KEY?: string; BAR_KEY?: string; BAR_REGION?: string; }>’.ts(2339)

It works if you do result.success === false. But !result.success doesn’t work…

This has nothing to do with strict mode.

@amany9000 There’s a quite easy workaround

Same, currenty facing this issue

No it isn’t

import { z } from 'zod'

const check = (env) => {
    const parsedEnv = z.string().safeParse(env);

    if(parsedEnv.success === false) { 
        console.error(parsedEnv.error.message); 
        process.exit(1); 
    } else {
        console.log('success!')
    }
}
check('1')
check(1)

when run

% node zod-repro.mjs

success!
[
  {
    "code": "invalid_type",
    "expected": "string",
    "received": "number",
    "path": [],
    "message": "Expected string, received number"
  }
]

with: zod@^3.22.4

The issue is resolved already?

@colinhacks @Creative-Difficulty, I’m facing the same issue and the return type for safeParse() is also incorrect.

Same here. image

Workaround: console.error((parsedObject as { error: Error }).error);

This is still an issue

I have same problem, image image