cover-image

Zod Error

About

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:

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:

1Error #1: Code: invalid_type ~ Path: name ~ Message: Required | Error #2: Code: invalid_type ~ Path: pets[1] ~ Message: Expected string, received number

Open source

The project is Open Source and can be viewed on GitHub & NPM.

Features

  • Options to customize the code component of the error message.
  • Options to customize the message component of the error message.
  • Options to customize the code path of the error message.
  • Set the delimiter between error messages and between components.
  • Set the maximum amount of error messages to display in final concatenated string.
  • Add a prefix to the start of the final concatenated message.
  • Add a suffix to the end of the final concatenated string.
  • Custom function to transform the format of each error message.

Technologies used

Examples

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:

1Error #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:

1Zod Path: ["dates", "purchased"] - Expected date, received string | Zod Path: ["dates", "fulfilled"] - Required

parse<T>(schema: z.ZodSchema<T>, data: unknown, options?: ErrorMessageOptions): T

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:

1👉 <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, use parseAsync() instead.

safeParse<T>(schema: z.ZodSchema<T>, data: unknown, options?: ErrorMessageOptions): SafeParseReturnType<T>

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}
36

Error Message:

1Time: 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, use safeParseAsync() instead.