In Zod 4, how should a command-line tool print a config-file validation failure, and why not print the ZodError's message property?
answer
- a built-in printer since version 4
- one cross mark per issue
- a dotted path with brackets
- message is a JSON dump
basics
~20 sPass the error to z.prettifyError, which returns one line per issue plus an arrow line with a dotted path, root-level issues first. A ZodError's message property is a pretty-printed JSON dump of the issues array, written for machines.
solid answer
~50 sIn Zod 4, `z.prettifyError(error)` returns a multi-line string: each issue becomes `✖ <message>`, followed by ` → at <path>` when it has a path, and issues are sorted by path length so root-level problems such as an unrecognized key come first. Paths render as `servers[0].port`: dots between keys, brackets around indexes and around keys that are not plain identifiers. That suits a terminal or a log line. The `message` property of a ZodError, by contrast, is a JSON string of the whole `issues` array, built the first time you read it, which is noisy for a person. The format is fixed: `prettifyError` takes no options, so for a different layout iterate `error.issues` yourself. In a CLI, call `safeParse`, print the prettified text to stderr and exit non-zero. Inputs stay out of the output, because issues drop `input` unless `reportInput` was set.
code
typescript · 14 linesimport * as z from "zod";
import { readFileSync } from "node:fs";
const Config = z.strictObject({
name: z.string(),
servers: z.array(z.object({ host: z.string(), port: z.int().min(1).max(65535) })),
});
const raw: unknown = JSON.parse(readFileSync("app.config.json", "utf8"));
const result = Config.safeParse(raw);
if (!result.success) {
console.error("app.config.json is invalid:\n" + z.prettifyError(result.error));
process.exit(1);
}go deeper
Recall z.prettifyError for turning a ZodError into readable text, and that printing err.message gives a JSON dump instead.
Explain the output: one cross-marked line per issue, an arrow line with a dotted and bracketed path, and root-level issues first.
Show the full CLI pattern, safeParse then stderr then a non-zero exit, and know when to drop to iterating issues for codes or a custom layout.
Decide whether human-facing tools share one formatting convention, since a fixed prettified format is cheap but cannot carry codes or colour without custom code.
## The scenario A command-line tool reads `app.config.json` at startup and validates it with a Zod schema before doing anything else. When the file is wrong, the user needs a short, readable explanation of what to fix, and the tool should exit with a failing status. Zod 4 gives you a function for exactly this: **`z.prettifyError`**. ## What z.prettifyError produces `z.prettifyError(error)` takes a ZodError and returns a string: - each issue becomes a line `✖ <message>`; - if the issue has a non-empty `path`, a second line ` → at <path>` follows; - issues are **sorted by path length**, so problems with the file as a whole (path `[]`), such as an unrecognized top-level key on a `z.strictObject`, come first, then shallow fields, then deep ones. Paths are rendered in a familiar property-access style: | Path array | Printed as | |---|---| | `['name']` | `name` | | `['servers', 0, 'port']` | `servers[0].port` | | `['labels', 'team-a']` | `labels["team-a"]` | Keys that are not plain identifiers (they contain a hyphen or a space, for example) are printed in brackets with quotes; numeric indexes are printed in brackets. The format is not configurable: the function takes the error and nothing else. Zod's release notes for version 4 say as much, and point out that the third-party `zod-validation-error` package filled this gap before. ## Why not error.message A ZodError is an `Error`, so it has a `message` property, and many CLIs print `err.message` by habit. In Zod 4 that property is a **pretty-printed JSON serialisation of the entire `issues` array**, computed the first time it is read. It is complete and machine-friendly, but for a person it is a wall of braces and quotes: - every issue appears as a multi-line JSON object; - paths are arrays rather than readable locations; - code-specific fields such as `origin` and `inclusive` add noise a user does not need. Printing the whole error object with `console.error(err)` has a similar problem, plus a stack trace that points into your validation code rather than at the config file. ## A sound CLI pattern 1. Read and `JSON.parse` the file; a syntax error is a different failure and deserves its own message. 2. Call `safeParse` rather than `parse`, so you handle the failure as data instead of catching an exception. 3. On failure, print a heading naming the file, then `z.prettifyError(result.error)`, to standard error. 4. Exit with a non-zero status so scripts and CI notice. Example output for a file with an extra `debug` key and a port written as a string: ```plaintext ✖ Unrecognized key: "debug" ✖ Invalid input: expected number, received string → at servers[0].port ``` ## What it does not print - **Input values.** Issues drop their `input` unless the parse ran with `reportInput: true`, and `prettifyError` prints only messages and paths, so a secret in the config file is not echoed. Zod's default messages name types and rule parameters, not submitted values, although a custom error function that interpolates the input would bring it back. - **Codes.** If a tool needs to react programmatically, for example to suggest a fix for `unrecognized_keys`, read `error.issues` and branch on `code` before or instead of prettifying. ## Printing versus structured logging A terminal is read by a person; a server log is often read by a machine first. The two want different things: - for a terminal or a single human-read log line, the prettified string is ideal; - for line-based log pipelines, the multi-line string splits one failure across several records, so log the `issues` array (code, path, message) as structured fields instead; - in both cases the default omission of `input` keeps submitted values out, as long as nobody turns on `reportInput` for convenience. A useful habit is to log the structured issues and show the prettified text, deriving both from the same `error` object. ## When to write your own formatter `prettifyError` is a sensible default for terminals and log lines. Write your own loop over `issues` when you need: - a different layout, such as one line per issue for a log aggregator; - colour or grouping by top-level section; - the codes alongside the messages; - paths in a different notation that your users already know. For field-keyed lookups (a form rather than a terminal), the structured helpers `z.flattenError` and `z.treeifyError` fit better than a string.
- In Zod 4, can z.prettifyError be told to use a different layout?No. It takes only the error and always prints a cross-marked message line plus an arrow line with the path, sorted by path length. For another layout, colour or codes, loop over `error.issues` and render `code`, `path` and `message` yourself.
- Why prefer safeParse over parse when validating a CLI's config file?`safeParse` returns the failure as a value, so the tool can print the prettified issues and choose its exit code in ordinary control flow. With `parse` the error is thrown, and an uncaught throw prints the error object, including its JSON `message` and a stack trace, which is the noisy output you were trying to avoid.
- A ZodError's message is a short summary of the first issue.
- z.prettifyError accepts options to change its layout.
- z.prettifyError prints the failing values, so secrets end up in logs.
- Pretty-printing Zod 4 errors needs a third-party package.
- z.prettifyError lists issues in schema declaration order.
Assumes Zod 4; z.prettifyError was added in Zod 4 as an official replacement for third-party pretty-printing.