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 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.
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()
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.
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.
Note — If you have issues with a path
longer than one level, this function throws away some error information.