💎 Zod 4 is now stable!  Read the announcement.
Zod logo

格式化錯誤 (Formatting errors)

Zod 在錯誤報告中強調 完整性正確性。在許多情況下,將 $ZodError 轉換為更有用的格式很有幫助。Zod 為此提供了一些實用程序。

考慮這個簡單的對象架構。

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

嘗試解析此無效數據會導致包含三個問題的錯誤。

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()

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 讓您可以更深入地遍歷樹。

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() 提供了錯誤的人類可讀字串表示形式。

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

這將返回以下字串:

✖ 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() 來檢索乾淨、淺層的錯誤對象。

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 對象為架構中的每個字段提供錯誤數組。

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

On this page