Zod logo

自定义错误

在 Zod 中,验证错误会显示为 z.core.$ZodError 类的实例。

¥In Zod, validation errors are surfaced as instances of the z.core.$ZodError class.

zod/v4 包使用了 z.ZodError 的子类 z.ZodError,该子类实现了一些便捷的方法。

¥The zod/v4 package uses a subclass of this called z.ZodError that implements some additional convenience methods.

$ZodError 的实例包含一个 .issues 数组。每个问题都包含一个易于阅读的 message 以及有关该问题的其他结构化元数据。

¥Instances of $ZodError contain an .issues array. Each issue contains a human-readable message and additional structured metadata about the issue.

import { z } from "zod/v4";
 
const result = z.string().safeParse(12); // { success: false, error: ZodError }
result.error.issues;
// [
//   {
//     expected: 'string',
//     code: 'invalid_type',
//     path: [],
//     message: 'Invalid input: expected string, received number'
//   }
// ]

每个问题都包含一个 message 属性,其中包含一条人性化的错误信息。错误消息可以通过多种方式自定义。

¥Every issue contains a message property with a human-readable error message. Error messages can be customized in a number of ways.

error 参数

¥The error param

几乎所有 Zod API 都接受可选的错误消息。

¥Virtually every Zod API accepts an optional error message.

z.string("Not a string!");

此自定义错误将显示为源自此 Schema 的任何验证问题的 message 属性。

¥This custom error will show up as the message property of any validation issues that originate from this schema.

z.string("Not a string!").parse(12);
// ❌ throws ZodError {
//   issues: [
//     {
//       expected: 'string',
//       code: 'invalid_type',
//       path: [],
//       message: 'Not a string!'   <-- 👀 custom error message
//     }
//   ]
// }

所有 z 函数和模式方法都接受自定义错误。

¥All z functions and schema methods accept custom errors.

z.string("Bad!");
z.string().min(5, "Too short!");
z.uuid("Bad UUID!");
z.iso.date("Bad date!");
z.array(z.string(), "Not an array!");
z.array(z.string()).min(5, "Too few items!");
z.set(z.string(), "Bad set!");

如果你愿意,可以传递一个带有 error 参数的 params 对象。

¥If you prefer, you can pass a params object with an error parameter instead.

z.string({ error: "Bad!" });
z.string().min(5, { error: "Too short!" });
z.uuid({ error: "Bad UUID!" });
z.iso.date({ error: "Bad date!" });
z.array(z.string(), { error: "Bad array!" });
z.array(z.string()).min(5, { error: "Too few items!" });
z.set(z.string(), { error: "Bad set!" });

error 参数可以选择接受一个函数。在 Zod 术语中,错误自定义函数称为错误映射。如果发生验证错误,错误映射将在解析时返回。

¥The error param optionally accepts a function. An error customization function is known as an error map in Zod terminology. The error map will can at parse time if a valiation error occurs.

z.string({ error: ()=>`[${Date.now()}]: Validation failure.` });

注意 — 在 Zod v3 中,message(字符串)和 errorMap(函数)有单独的参数。这些在 Zod 4 中已统一为 error

¥Note — In Zod v3, there were separate params for message (a string) and errorMap (a function). These have been unified in Zod 4 as error.

错误映射接收一个上下文对象,你可以使用它根据验证问题自定义错误消息。

¥The error map receives a context object you can use to customize the error message based on the validation issue.

z.string({
  error: (iss) => iss.input === undefined ? "Field is required." : "Invalid input."
});

对于高级情况,iss 对象提供了可用于自定义错误的附加信息。

¥For advanced cases, the iss object provides additional information you can use to customize the error.

z.string({
  error: (iss) => {
    iss.code; // the issue code
    iss.input; // the input data
    iss.inst; // the schema/check that originated this issue
    iss.path; // the path of the error
  },
});

根据你使用的 API,可能会有更多可用属性。使用 TypeScript 的自动补齐功能探索可用属性。

¥Depending on the API you are using, there may be additional properties available. Use TypeScript's autocomplete to explore the available properties.

z.string().min(5, {
  error: (iss) => {
    // ...the same as above
    iss.minimum; // the minimum value
    iss.inclusive; // whether the minimum is inclusive
    return `Password must have ${iss.minimum} characters or more`;
  },
});

返回 undefined 以避免设置错误消息。这对于自定义某些错误消息(而非其他错误消息)非常有用。Zod 将把控制权交给 优先级链 中的下一个错误图。

¥Return undefined to avoid setting an error message. This is useful for customizing certain error messages but not others. Zod will yield control to the next error map in the precedence chain.

z.int64({
  error: (issue) => {
    // override too_big error message
    if (issue.code === "too_big") {
      return { message: `Value must be <${issue.maximum}` };
    }
 
    //  defer to default
    return undefined;
  },
});

每次解析错误自定义

¥Per-parse error customization

要根据每次解析自定义错误,请将错误映射传递给解析方法:

¥To customize errors on a per-parse basis, pass an error map into the parse method:

const schema = z.string()
 
schema.parse(12, {
  error: iss => "per-parse custom error"
};

此方法的优先级低于任何模式级自定义消息。

¥This has lower precedence than any schema-level custom messages.

const schema = z.string({ error: "highest priority" });
const result = schema.safeParse(12, {
  error: (iss) => "lower priority",
})
 
result.error.issues;
// [{ message: "highest priority", ... }]

iss 对象是所有可能问题类型的 可区分联合。使用 code 属性来区分它们。

¥The iss object is a discriminated union of all possible issue types. Use the code property to discriminate between them.

有关所有 Zod 问题代码的详细说明,请参阅 zod/v4/core 文档。

¥For a breakdown of all Zod issue codes, see the zod/v4/core documentation.

const result = schema.safeParse(12, {
  error: (iss) => {
    if (iss.code === "invalid_type") {
      return `invalid type, expected ${iss.expected}`;
    }
    if (iss.code === "too_small") {
      return `minimum is ${iss.minimum}`;
    }
    // ...
  }
})

全局错误自定义

¥Global error customization

要指定全局错误映射,请使用 z.config() 设置 Zod 的 customError 配置设置:

¥To specify a global error map, use z.config() to set Zod's customError configuration setting:

z.config({
  customError: (iss) => {
    return "globally modified error";
  },
});

全局错误消息的优先级低于模式级或每次解析时产生的错误消息。

¥Global error messages have lower precedence than schema-level or per-parse error messages.

iss 对象是所有可能问题类型的 可区分联合。使用 code 属性来区分它们。

¥The iss object is a discriminated union of all possible issue types. Use the code property to discriminate between them.

有关所有 Zod 问题代码的详细说明,请参阅 zod/v4/core 文档。

¥For a breakdown of all Zod issue codes, see the zod/v4/core documentation.

const result = schema.safeParse(12, {
  error: (iss) => {
    if (iss.code === "invalid_type") {
      return `invalid type, expected ${iss.expected}`;
    }
    if (iss.code === "too_small") {
      return `minimum is ${iss.minimum}`;
    }
    // ...
  }
})

国际化

¥Internationalization

为了支持错误消息的国际化,Zod 提供了几种内置的语言环境。这些从 zod/v4/core 包导出。

¥To support internationalization of error message, Zod provides several built-in locales. These are exported from the zod/v4/core package.

注意zod/v4 库会自动加载 en 语言环境。zod/v4-mini 子包不加载任何语言环境;所有错误消息都默认为 Invalid input

¥— The zod/v4 library automatically loads the en locale automatically. The zod/v4-mini sub-package does not load any locale; instead all error messages default to Invalid input.

import { z } from "zod/v4";
import en from "zod/v4/locales/en.js"
 
z.config(en());

要延迟加载语言环境,请考虑使用动态导入:

¥To lazily load a locale, consider dynamic imports:

import { z } from "zod/v4";
 
async function loadLocale(locale: string) {
  const { default: locale } = await import(`zod/v4/locales/${locale}.js`);
  z.config(locale());
};
 
await loadLocale("fr");

为了方便起见,所有语言环境都从 zod/v4/locales 导出为 z.locales

¥For convenience, all locales are exported as z.locales from zod/v4/locales.

import { z } from "zod/v4";
 
z.config(z.locales.en());

语言环境

¥Locales

以下语言环境可用:

¥The following locales are available:

  • ar — 阿拉伯语

    ¥ar — Arabic

  • az — 阿塞拜疆语

    ¥az — Azerbaijani

  • be — 白俄罗斯语

    ¥be — Belarusian

  • ca — 加泰罗尼亚语

    ¥ca — Catalan

  • cs — 捷克语

    ¥cs — Czech

  • de — 德语

    ¥de — German

  • en — 英语

    ¥en — English

  • es — 西班牙语

    ¥es — Spanish

  • fa — 波斯语

    ¥fa — Farsi

  • fi — 芬兰语

    ¥fi — Finnish

  • fr — 法语

    ¥fr — French

  • frCA — 加拿大法语

    ¥frCA — Canadian French

  • he — 希伯来语

    ¥he — Hebrew

  • hu — 匈牙利语

    ¥hu — Hungarian

  • id — 印尼语

    ¥id — Indonesian

  • it — 意大利语

    ¥it — Italian

  • ja — 日语

    ¥ja — Japanese

  • ko — 韩语

    ¥ko — Korean

  • mk — 马其顿语

    ¥mk — Macedonian

  • ms — 马来语

    ¥ms — Malay

  • no — 挪威语

    ¥no — Norwegian

  • ota — 土耳其语

    ¥ota — Türkî

  • pl — 波兰语

    ¥pl — Polish

  • pt —葡萄牙语

    ¥pt — Portuguese

  • ru — 俄语

    ¥ru — Russian

  • sl — 斯洛文尼亚语

    ¥sl — Slovenian

  • ta — 泰米尔语

    ¥ta — Tamil

  • th — 泰语

    ¥th — Thai

  • tr — 土耳其语

    ¥tr — Türkçe

  • ua — 乌克兰语

    ¥ua — Ukrainian

  • ur — 乌尔都语

    ¥ur — Urdu

  • vi — 越南语

    ¥vi — Tiếng Việt

  • zhCN — 简体中文

    ¥zhCN — Simplified Chinese

  • zhTW — 繁体中文

    ¥zhTW — Traditional Chinese

错误优先级

¥Error precedence

以下是确定错误优先级的快速参考:如果定义了多个错误自定义,哪一个优先?优先级从高到低:

¥Below is a quick reference for determining error precedence: if multiple error customizations have been defined, which one takes priority? From highest to lowest priority:

  1. 模式级错误 - 任何错误消息 "硬编码" 都会进入模式定义。

    ¥Schema-level error — Any error message "hard coded" into a schema definition.

z.string("Not a string!");
  1. 每次解析错误 - 传递给 .parse() 方法的自定义错误映射。

    ¥Per-parse error — A custom error map passed into the .parse() method.

z.string().parse(12, {
  error: (iss) => "My custom error"
});
  1. 全局错误映射 - 传递给 z.config() 的自定义错误映射。

    ¥Global error map — A custom error map passed into z.config().

z.config({
  customError: (iss) => "My custom error"
});
  1. 区域设置错误映射 - 传入 z.config() 的自定义错误映射。

    ¥Locale error map — A custom error map passed into z.config().

z.config(z.locales.en());

On this page