Zod logo

格式错误

Zod 在其错误报告中强调 完整性正确性。在许多情况下,将 $ZodError 转换为更有用的格式是很有帮助的。Zod 提供了一些工具来实现这一点。

🌐 Zod emphasizes completeness and correctness in its error reporting. In many cases, it's helpful to convert the $ZodError to a more useful format. Zod provides some utilities for this.

考虑这个简单的对象模式。

🌐 Consider this simple object schema.

import * as z from "zod";
 
const schema = z.strictObject({
  username: z.string(),
  favoriteNumbers: z.array(z.number()),
});

尝试解析此无效数据会导致包含三个问题的错误。

🌐 Attempting to parse this invalid data results in an error containing three issues.

const result = schema.safeParse({
  username: 1234,
  favoriteNumbers: [1234, "4567"],
  extraKey: 1234,
});
 
result.error!.issues;
[
  {
    expected: 'string',
    code: 'invalid_type',
    path: [ 'username' ],
    message: 'Invalid input: expected string, received number'
  },
  {
    expected: 'number',
    code: 'invalid_type',
    path: [ 'favoriteNumbers', 1 ],
    message: 'Invalid input: expected number, received string'
  },
  {
    code: 'unrecognized_keys',
    keys: [ 'extraKey' ],
    path: [],
    message: 'Unrecognized key: "extraKey"'
  }
];

z.treeifyError()

要将此错误转换(“树形化”)为嵌套对象,请使用 z.treeifyError()

🌐 To convert ("treeify") this error into a nested object, use z.treeifyError().

const tree = z.treeifyError(result.error);
 
// =>
{
  errors: [ 'Unrecognized key: "extraKey"' ],
  properties: {
    username: { errors: [ 'Invalid input: expected string, received number' ] },
    favoriteNumbers: {
      errors: [],
      items: [
        undefined,
        {
          errors: [ 'Invalid input: expected number, received string' ]
        }
      ]
    }
  }
}

结果是一个嵌套结构,反映了模式本身。你可以轻松访问在特定路径发生的错误。errors 字段包含给定路径的错误信息,而特殊属性 propertiesitems 允许你深入遍历树结构。

🌐 The result is a nested structure that mirrors the schema itself. You can easily access the errors that occurred at a particular path. The errors field contains the error messages at a given path, and the special properties properties and items let you traverse deeper into the tree.

tree.properties?.username?.errors;
// => ["Invalid input: expected string, received number"]
 
tree.properties?.favoriteNumbers?.items?.[1]?.errors;
// => ["Invalid input: expected number, received string"];

请务必使用可选链(?.)以避免在访问嵌套属性时出错。

z.prettifyError()

z.prettifyError() 提供了错误的人类可读字符串表示。

🌐 The z.prettifyError() provides a human-readable string representation of the error.

const pretty = z.prettifyError(result.error);

这将返回以下字符串:

🌐 This returns the following string:

✖ Unrecognized key: "extraKey"
✖ Invalid input: expected string, received number
  → at username
✖ Invalid input: expected number, received string
  → at favoriteNumbers[1]

z.formatError()

此功能已被弃用,建议使用 z.treeifyError()

z.flattenError()

虽然 z.treeifyError() 对于遍历可能复杂的嵌套结构很有用,但大多数模式是扁平的——只有一层。在这种情况下,使用 z.flattenError() 来获取干净的、浅层的错误对象。

🌐 While z.treeifyError() is useful for traversing a potentially complex nested structure, the majority of schemas are flat—just one level deep. In this case, use z.flattenError() to retrieve a clean, shallow error object.

const flattened = z.flattenError(result.error);
// { errors: string[], properties: { [key: string]: string[] } }
 
{
  formErrors: [ 'Unrecognized key: "extraKey"' ],
  fieldErrors: {
    username: [ 'Invalid input: expected string, received number' ],
    favoriteNumbers: [ 'Invalid input: expected number, received string' ]
  }
}

formErrors 数组包含任何顶层错误(其中 path[])。fieldErrors 对象为模式中的每个字段提供一个错误数组。

🌐 The formErrors array contains any top-level errors (where path is []). The fieldErrors object provides an array of errors for each field in the schema.

flattened.fieldErrors.username; // => [ 'Invalid input: expected string, received number' ]
flattened.fieldErrors.favoriteNumbers; // => [ 'Invalid input: expected number, received string' ]

On this page