zod icon indicating copy to clipboard operation
zod copied to clipboard

Access, manipulate, and throw error from `z.catch`

Open MMZK1526 opened this issue 5 months ago • 3 comments

If I understand correctly, z.catch always catches all errors, and it is not possible to only catch on certain cases and rethrow the error in other cases.

For example, if I want an API_KEY to have a hardcoded default value only when the global variable env is "dev", I might do something like this:

...
"API_KEY": z.string()
  .catch(function () {
    if (env === "dev") return defaultValue;
  }).pipe(z.string()),
...

Note that I have to try to parse the entire result as a string again in the pipe, so that if I'm not in dev mode, the catch turns the key into undefined which fails the second z.string().

Ideally I would imagine being able to "rethrow" the error in the catch.

MMZK1526 avatar Sep 20 '24 10:09 MMZK1526