Formatting errors
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()
To convert ("treeify") this error into a nested object, use z.treeifyError()
.
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()
The z.prettifyError()
provides a human-readable string representation of the error.
This returns the following string:
z.formatError()
This has been deprecated in favor of z.treeifyError()
.
z.flattenError()
This has been deprecated in favor of z.treeifyError()
.