Zod Error converts and formats zod Issues into a customizable error message string that can be consumed by various applications such as front-end error message modals or API error messages.
Error messages are completely customizable from label names to delimiters, prefixes, suffixes and the inclusion/exclusion of components (code, path, message). An options argument can be passed to any Zod Error function as the last argument to customize the error message.
Zod Error converts an array of Zod Issues that look like this:
into this:
The project is Open Source and can be viewed on GitHub & NPM.
There are 6 ways to consume Zod Error. generateErrorMessage()
, generateError()
, parse()
, parseAsync()
, safeParse()
and safeParseAsync()
.
Formats an array of Zod Issues as a result of z.parse()
, z.parseAsync()
, z.safeParse()
or z.safeParseAsync()
and outputs as a single string. Multiple errors are concatenated into a single readable string.
Output:
Formats an array of Zod Issues as a result of z.parse()
, z.parseAsync()
, z.safeParse()
or z.safeParseAsync()
and outputs as a JavaScript Error object. Multiple errors are concatenated into a single readable string.
Output:
Replaces Zod's .parse()
function by replacing Zod's ZodError
with a generic JavaScript Error
object where the custom-formatted message can be accessed on error.message
.
Output:
Note:
If your schema contains an async .refine()
or .transform()
function, use parseAsync()
instead.
Replaces Zod's .safeParse()
function by replacing Zod's SafeParseReturnType
with a similar return type where if result.success
is false
, the custom formatted error message will be available on result.error.message
.
Output:
Note:
If your schema contains an async .refine()
or .transform()
function, use safeParseAsync()
instead.