格式错误
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.
尝试解析此无效数据会导致包含两个问题的错误。
¥Attempting to parse this invalid data results in an error containing two issues.
z.treeifyError()
要将此错误 ("treeify") 转换为嵌套对象,请使用 z.treeifyError()
。
¥To convert ("treeify") this error into a nested object, use z.treeifyError()
.
结果是一个嵌套结构,它镜像了模式本身。你可以轻松访问特定路径上发生的错误。errors
字段包含给定路径的错误消息,特殊属性 properties
和 items
允许你更深入地遍历树。
¥The result is a nested structure that mirrors the schema itself. You can easily access the errors that occured 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.
请务必使用可选链 (?.
) 来避免访问嵌套属性时出错。
¥Be sure to use optional chaining (?.
) to avoid errors when accessing nested properties.
z.prettifyError()
z.prettifyError()
提供错误信息的人性化字符串表示。
¥The z.prettifyError()
provides a human-readable string representation of the error.
这将返回以下字符串:
¥This returns the following string:
z.formatError()
此方法已被弃用,取而代之的是 z.treeifyError()
。
¥This has been deprecated in favor of z.treeifyError()
.
z.flattenError()
此方法已被弃用,取而代之的是 z.treeifyError()
。
¥This has been deprecated in favor of z.treeifyError()
.