Format errors generated by zod
into simple and easy-to-understand messages.
- Each issue is prefixed by a path, except for top-level issues.
- Union errors are simplified, especially for simple cases like
string | number
. - Aggregated error messages are generated: a single line for single-issue errors and multiline for multi-issue errors.
The error message deliberately excludes the actual input passed to the schema parser. While this information could be helpful in certain cases, including it poses a risk of leaking sensitive information such as passwords or payment details. By omitting input data from error messages, we prioritize security and privacy. Instead, we provide the type of the input data to aid developers in understanding validation errors without compromising data privacy.
Input:
import { safeParse } from '@schema-hub/zod-error-formatter';
const schema = z.union([z.string(), z.number()]);
const result = safeParse(schema, true);
Error message:
Validation failed: invalid value: expected one of string or number, but got boolean
npm install @schema-hub/zod-error-formatter
Formats an instance of ZodError
into a new Error
instance with aggregated and formatted messages, along with an issues
array containing all individual formatted issues.
Wraps zod
's schema.parse(inputData)
method and automatically formats any thrown ZodError
.
Wraps zod
's schema.safeParse(inputData)
method and automatically formats any ZodError
in the failure result.