UNPKG

@schema-hub/zod-error-formatter

Version:

Simple and easy-to-understand zod error messages

51 lines (30 loc) 1.78 kB
# zod-error-formatter Format errors generated by [`zod`](https://github.com/colinhacks/zod) into simple and easy-to-understand messages. ## How it Works - 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. ### Design Notes 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. ## Example Input: ```typescript 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 ``` ## Installation ```bash npm install @schema-hub/zod-error-formatter ``` ## Usage ### `formatZodError(zodError, inputData)` 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. ### `parse(schema, inputData)` Wraps `zod`'s `schema.parse(inputData)` method and automatically formats any thrown `ZodError`. ### `safeParse(schema, inputData)` Wraps `zod`'s `schema.safeParse(inputData)` method and automatically formats any `ZodError` in the failure result.