Gathering detailed insights and metrics for zod-error
Gathering detailed insights and metrics for zod-error
Gathering detailed insights and metrics for zod-error
Gathering detailed insights and metrics for zod-error
zod-validation-error
Wrap zod validation errors in user-friendly readable messages
zod-i18n-map
A library for localizing zod error messages.
@schema-hub/zod-error-formatter
Simple and easy-to-understand zod error messages
@ocubist/error-alchemy
A powerful Node.js error-handling-framework with custom error types for easy debugging, enhanced error management, strong zod-support and useful quality-of-life-functionality for asserting and validating values.
npm install zod-error
Typescript
Module System
Node Version
NPM Version
99.4
Supply Chain
100
Quality
75.7
Maintenance
100
Vulnerability
100
License
TypeScript (100%)
Total Downloads
4,967,310
Last Day
14,640
Last Week
85,130
Last Month
367,370
Last Year
3,162,418
MIT License
53 Stars
48 Commits
1 Watchers
1 Branches
1 Contributors
Updated on Apr 17, 2025
Minified
Minified + Gzipped
Latest Version
1.5.0
Package Id
zod-error@1.5.0
Unpacked Size
65.16 kB
Size
13.05 kB
File Count
73
NPM Version
8.19.3
Node Version
19.2.0
Published on
Feb 22, 2023
Cumulative downloads
Total Downloads
Last Day
-5.7%
14,640
Compared to previous day
Last Week
-7.3%
85,130
Compared to previous week
Last Month
-1.4%
367,370
Compared to previous month
Last Year
121.2%
3,162,418
Compared to previous year
Utilities to format and customize Zod error messages.
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.
Zod Error converts an array of Zod Issues that look like this:
1[ 2 { 3 code: 'invalid_type', 4 expected: 'string', 5 received: 'undefined', 6 path: ['name'], 7 message: 'Required', 8 }, 9 { 10 code: 'invalid_type', 11 expected: 'string', 12 received: 'number', 13 path: ['pets', 1], 14 message: 'Expected string, received number', 15 }, 16];
into this:
Error #1: Code: invalid_type ~ Path: name ~ Message: Required | Error #2: Code: invalid_type ~ Path: pets[1] ~ Message: Expected string, received number
Install the package using your favorite package manager:
npm install zod-error
yarn add zod-error
pnpm add zod-error
🕓 2022-07-14T20:19:52.290Z ~ Error #1: Code: invalid_type ~ Path: ratings[0].speed ~ Message: Expected number, received string 🔥 Error #2: Code: invalid_enum_value ~ Path: position ~ Message: Invalid enum value. Expected 'C' | 'PF' | 'SF' | 'SG' | 'PG', received 'Center'🔚
Value | Description |
---|---|
🕓 2022-07-14T20:19:15.660Z ~ | Prefix |
~ | Component delimiter |
Error #1: | Added using options.transform() |
Code: | Code label |
invalid_type | Code value |
Path: | Path label |
ratings[0].speed | Path value |
Message: | Message label |
Expected number, received string | Message value |
🔥 | Error delimiter |
Error #2: Code: invalid_enum_value ~ Path: position ~ Message: Invalid enum value. Expected 'C' | 'PF' | 'SF' | 'SG'| 'PG', received 'Center' | Error from second ZodIssue from Issues array input |
🔚 | Suffix |
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.
Property | Value | Description |
---|---|---|
code? | CodeOptions | Options to customize the code component of the error message. |
delimiter? | DelimiterOptions | Set the delimiter between error messages and between components. |
maxErrors? | number | Maximum amount of error messages to display in final concatenated string. |
message? | MessageOptions | Options to customize the message component of the error message. |
path? | PathOptions | Options to customize the code path of the error message. |
prefix? | string | Add a prefix to the start of the final concatenated message. |
suffix? | string | Add a suffix to the end of the final concatenated string. |
transform? | (params: TransformErrorParams) => string | A custom function to transform the format of each error message. |
Property | Value | Description |
---|---|---|
enabled | boolean | Display or hide the code component of the error message. Defaults to true . |
label? | string | null | Set a custom label. Defaults to Code: . Only available if enabled is true . |
transform? | (params: TransformComponentParams) => string | A custom function to transform the format of the code component. Only available if enabled is true . |
Property | Value | Description |
---|---|---|
component? | string | The delimiter between each component during the concatentation process. Defaults to ~ . |
error? | string | The delimiter between each error message during the concatentation process. Defaults to | . |
Property | Value | Description |
---|---|---|
enabled | boolean | Display or hide the message component of the error message. Defaults to true . |
label? | string | null | Set a custom label. Defaults to Message: . Only available if enabled is true . |
transform? | (params: TransformComponentParams) => string | A custom function to transform the format of the message component. Only available if enabled is true . |
Property | Value | Description |
---|---|---|
arraySquareBrackets? | boolean | Adds square brackets around index number in the path. Only available if enabled is true and type is objectNotation or breadcrumbs . Defaults to true . |
delimiter? | string | Set a custom delimeter between each path element. Only available if enabled is true and type is breadcrumbs . Defaults to > . |
enabled | boolean | Display or hide the path component of the error message. Defaults to true . |
label? | string | null | Set a custom label. Defaults to Message: . Only available if enabled is true . |
transform? | (params: TransformComponentParams) => string | A custom function to transform the format of the message component. Only available if enabled is true . |
type | 'objectNotation' | 'zodPathArray' | 'breadcrumbs' | Sets the style of the path string. objectNotation = car.wheels[1].tyre zodPathArray = ["car", "wheels", 1, "tyre"] breadcrumbs = car > wheels > [1] > tyre. |
Property | Value | Description |
---|---|---|
component | string | The transformed component string. Defaults to ${label}${value} . |
label | string | The label of the component. |
value | string | The value of the component. |
Property | Value | Description |
---|---|---|
codeComponent | string | The transformed code component string. Defaults to ${label}${value} . |
errorMessage | string | The transformed error message consisting of all components concatentated. |
index | string | The index of the current error message. |
issue | z.ZodIssue | The original ZodIssue object. |
messageComponent | string | The transformed message component string. Defaults to ${label}${value} . |
pathComponent | string | The transformed path component string. Defaults to ${label}${value} . |
There are 6 ways to consume Zod Error. generateErrorMessage()
, generateError()
, parse()
, parseAsync()
, safeParse()
and safeParseAsync()
.
generateErrorMessage(issues: z.ZodIssue[], options?: ErrorMessageOptions): string
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.
1import { generateErrorMessage, ErrorMessageOptions } from 'zod-error'; 2import { z } from 'zod'; 3 4enum Color { 5 Red = 'Red', 6 Blue = 'Blue', 7} 8 9const options: ErrorMessageOptions = { 10 delimiter: { 11 error: ' 🔥 ', 12 }, 13 transform: ({ errorMessage, index }) => `Error #${index + 1}: ${errorMessage}`, 14}; 15 16const schema = z.object({ 17 color: z.nativeEnum(Color), 18 shape: z.string(), 19 size: z.number().gt(0), 20}); 21 22const data = { 23 color: 'Green', 24 size: -1, 25}; 26 27const result = schema.safeParse(data); 28if (!result.success) { 29 const errorMessage = generateErrorMessage(result.error.issues, options); 30 throw new Error(errorMessage); 31}
Error Message:
Error #1: Code: invalid_enum_value ~ Path: color ~ Message: Invalid enum value. Expected 'Red' | 'Blue', received 'Green' 🔥 Error #2: Code: invalid_type ~ Path: shape ~ Message: Required 🔥 Error #3: Code: too_small ~ Path: size ~ Message: Number must be greater than 0
generateError(issues: z.ZodIssue[], options?: ErrorMessageOptions): Error
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.
1import { ErrorMessageOptions, generateError } from 'zod-error'; 2import { z } from 'zod'; 3 4const options: ErrorMessageOptions = { 5 maxErrors: 2, 6 delimiter: { 7 component: ' - ', 8 }, 9 path: { 10 enabled: true, 11 type: 'zodPathArray', 12 label: 'Zod Path: ', 13 }, 14 code: { 15 enabled: false, 16 }, 17 message: { 18 enabled: true, 19 label: '', 20 }, 21}; 22 23const schema = z.object({ 24 dates: z.object({ 25 purchased: z.date(), 26 fulfilled: z.date(), 27 }), 28 item: z.string(), 29 price: z.number(), 30}); 31 32const data = { 33 dates: { purchased: 'yesterday' }, 34 item: 1, 35 price: '1,000', 36}; 37 38try { 39 schema.parse(data); 40} catch (error) { 41 const genericError = generateError(error, options); 42 throw genericError; 43}
Error Message:
Zod Path: ["dates", "purchased"] - Expected date, received string | Zod Path: ["dates", "fulfilled"] - Required
parse<T extends z.ZodTypeAny>(schema: T, data: unknown, options?: ErrorMessageOptions): T['_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
.
1import { ErrorMessageOptions, parse } from 'zod-error'; 2import { z } from 'zod'; 3 4const options: ErrorMessageOptions = { 5 delimiter: { 6 error: ' ', 7 }, 8 path: { 9 enabled: true, 10 type: 'objectNotation', 11 transform: ({ label, value }) => `<${label}: ${value}>`, 12 }, 13 code: { 14 enabled: true, 15 transform: ({ label, value }) => `<${label}: ${value}>`, 16 }, 17 message: { 18 enabled: true, 19 transform: ({ label, value }) => `<${label}: ${value}>`, 20 }, 21 transform: ({ errorMessage }) => `👉 ${errorMessage} 👈`, 22}; 23 24const schema = z.object({ 25 animal: z.enum(['🐶', '🐱', '🐵']), 26 quantity: z.number().gte(1), 27}); 28 29const data = { 30 animal: '🐼', 31 quantity: 0, 32}; 33 34try { 35 const safeData = parse(schema, data, options); 36 /** 37 * Asynchronous version 38 * const safeData = await parseAsync(schema, data, options); 39 */ 40} catch (error) { 41 /** 42 * Replaces ZodError with a JavaScript 43 * Error object with custom formatted message. 44 */ 45 if (error instanceof Error) { 46 console.error(error.message); 47 } 48}
Error Message:
👉 <Code: : invalid_enum_value> ~ <Path: : animal> ~ <Message: : Invalid enum value. Expected '🐶' | '🐱' | '🐵', received '🐼'> 👈 👉 <Code: : too_small> ~ <Path: : quantity> ~ <Message: : Number must be greater than or equal to 1> 👈
Note:
If your schema contains an async
.refine()
or.transform()
function, useparseAsync()
instead.
safeParse<T extends z.ZodTypeAny>(schema: T, data: unknown, options?: ErrorMessageOptions): SafeParseReturnType<T['_output']
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
.
1import { ErrorMessageOptions, safeParse } from 'zod-error'; 2import { z } from 'zod'; 3 4const options: ErrorMessageOptions = { 5 prefix: `Time: ${new Date().toISOString()} ~ `, 6 suffix: '🔚', 7}; 8 9const schema = z.object({ 10 id: z.string().uuid(), 11 timestamp: z.number(), 12 message: z.string().min(5), 13}); 14 15const data = { 16 id: 'ID001', 17 timestamp: new Date(), 18 message: 'lol!', 19}; 20 21const result = safeParse(schema, data, options); 22/** 23 * Asynchronous version 24 * const result = await safeParseAsync(schema, data, options); 25 */ 26if (!result.success) { 27 /** 28 * Replaces Zod's error object with custom 29 * error object with formatted message. 30 */ 31 const message = result.error.message; 32 console.error(message); 33} else { 34 const safeData = result.data; 35}
Error Message:
Time: 2022-07-14T11:10:10.602Z ~ Code: invalid_string ~ Path: id ~ Message: Invalid uuid | Code: invalid_type ~ Path: timestamp ~ Message: Expected number, received date | Code: too_small ~ Path: message ~ Message: String must contain at least 5 character(s)🔚
Note:
If your schema contains an async
.refine()
or.transform()
function, usesafeParseAsync()
instead.
See also the list of contributors who participated in this project.
No vulnerabilities found.
No security vulnerabilities found.