skip to content

Issue Formatting & Messages

A ZodError is a list of issues with codes and paths. Interviewers ask how you turn it into field-keyed messages a form can show, and what Zod 4 changed: the error param, flattenError, treeifyError.

on this pageshow

explore

questions

6

In Zod 4, what does the ZodError from a failed safeParse contain, and what do each issue's code, path and message tell you?

level: juniorimportance: must knowfreq 62%

answer

  1. an array, not one sentence
  2. machine field plus human field
  3. keys and indexes from the root
  4. extra fields depend on the code
  5. raw value left out by default

basics

~20 s

A Zod 4 ZodError holds an issues array, one entry per problem. Each issue carries a code naming the kind of failure, a path locating the bad value from the root, a human message, and code-specific fields such as expected or minimum.

solid answer

~50 s

`safeParse` returns `{ success: false, error }`, and `error.issues` lists every problem Zod found across the input, not just the first. Each issue has a `code` such as `invalid_type`, `too_small`, `invalid_format` or `unrecognized_keys`; a `path` of keys and array indexes from the root, so `['items', 3, 'qty']` points at one nested value and `[]` means the input as a whole; and a `message`, which the default English locale writes for you, for example "Invalid input: expected string, received undefined" for a missing field. Code-specific fields carry the parameters: `expected` on `invalid_type`; `origin`, `minimum` and `inclusive` on `too_small`; `keys` on `unrecognized_keys`. The raw input is left out by default so that logging issues does not echo submitted values; pass `reportInput: true` to the parse call to include it. Program logic should branch on `code` and the parameters, and people should see `message`.

code

typescript · 13 lines
typescript
import * as z from "zod";

const SignUp = z.object({
  email: z.string(),
  password: z.string().min(8),
});

const result = SignUp.safeParse({ password: "short" });
if (!result.success) {
  for (const issue of result.error.issues) {
    console.log(issue.code, issue.path, issue.message);
  }
}

go deeper

for a junior

Recall that a failed parse gives an issues array, and name code, path and message, with path being an array of keys and indexes from the root.

for a middle

Explain the code-specific fields such as expected, minimum and keys, why a missing field shows up as invalid_type, and that input is dropped unless reportInput is set.

for a senior

Show that you branch on code and parameters rather than message text, and that you keep reportInput out of production logging because issues would then carry raw request values.

for a principal

Treat the issue list as the contract between validation and every consumer: forms, logs and translations all derive from code, path and parameters, so a team standardises on reading those.

## What a failed parse hands you Zod validates **unknown** input against a schema. When you call `safeParse`, you get back a result object: either `{ success: true, data }` with the typed value, or `{ success: false, error }`. The `error` is a **ZodError**, and its useful content is one property: `issues`, an array with one object per problem. Zod keeps validating after the first failure wherever it can. An object schema checks every declared field, so a sign-up body with a missing email and a short password produces two issues, not one. (Inside a single field, a value of the wrong type stops there: Zod does not run `.min()` on a number that was supposed to be a string.) ## The fields every issue carries | Field | What it holds | Who reads it | |---|---|---| | `code` | the kind of failure, as a fixed string | your program | | `path` | an array of object keys and array indexes from the root | your program, to place the error | | `message` | a human-readable sentence | people | | code-specific fields | the parameters of the failed rule | your program, translations | - **`code`** is the stable, machine-readable part. Branch on it, never on the message text. - **`path`** is an array, not a dotted string. `['address', 'zip']` is a nested field; `['phones', 1]` is the second element of an array, because indexes start at zero; `[]` means the problem is with the input as a whole. - **`message`** comes from the error map chain. With no customisation, the English locale that the `zod` package loads writes it, for example `Too small: expected string to have >=8 characters`. ## The issue codes in Zod 4 Zod 4 has eleven issue codes. The common ones: | Code | Raised when | Extra fields | |---|---|---| | `invalid_type` | the value is the wrong JavaScript type, including a missing required key | `expected` | | `too_small` / `too_big` | a length, size or numeric bound fails | `origin`, `minimum` or `maximum`, `inclusive`, sometimes `exact` | | `invalid_format` | a string format such as an email or UUID fails | `format`, sometimes `pattern` | | `invalid_value` | a literal or enum gets a value outside its set | `values` | | `unrecognized_keys` | a strict object meets keys it does not declare | `keys` | | `invalid_union` | no union option matched | `errors` (one issue list per option) | | `custom` | a refinement failed | `params`, if given | The rest are `not_multiple_of`, `invalid_key` and `invalid_element` (for record, map and set keys and members). Notice what is missing: there is **no `required` code**. A required key that is absent reaches its field schema as `undefined`, so it fails as `invalid_type`, and the English message ends with `received undefined`. ## The input is excluded by default Each issue is created with the failing input attached, so error maps can look at it. When Zod finalises the issue, it **drops `input`** unless the parse call asked for it: ```ts schema.safeParse(body, { reportInput: true }); ``` The default exists so that logging a ZodError does not write passwords, tokens or personal data into your logs. Turn `reportInput` on for local debugging, not for production logging. ## Working with issues A worked example: a sign-up schema with a required `email` and a `password` of at least eight characters, parsed against `{ password: "short" }`. ```ts const SignUp = z.object({ email: z.string(), password: z.string().min(8) }); const result = SignUp.safeParse({ password: "short" }); // result.error.issues: // [{ expected: "string", code: "invalid_type", path: ["email"], // message: "Invalid input: expected string, received undefined" }, // { origin: "string", code: "too_small", minimum: 8, inclusive: true, // path: ["password"], message: "Too small: expected string to have >=8 characters" }] ``` A sensible order of use: 1. Check `result.success`; on failure, read `result.error.issues`. 2. Use `path` to attach each issue to a field, and `[]` paths to the form as a whole. 3. Use `code` and its parameters for logic and for translation keys. 4. Show `message` to people, or hand the issues to Zod's formatting helpers, which turn the array into a field-keyed object or a printable string. The issue list is the single source every consumer derives from: a form's field messages, a log line, a translated string. Understanding its fields is what makes the formatting helpers predictable.

  • In Zod 4, how can code tell a missing field from a field of the wrong type?
    Both fail as `invalid_type`, because a missing key reaches the field schema as `undefined`. Inside an error map, the raw issue still carries the input, so `iss.input === undefined` separates the two cases. The finalised issue drops `input` unless the parse ran with `reportInput: true`, so do the distinction inside the error map rather than afterwards.
  • What does a Zod 4 issue look like when a union matches none of its options?
    Zod reports one `invalid_union` issue at the union's path. Its `errors` property holds an array of issue lists, one per option it tried, and its default message is just "Invalid input". A discriminated union with an unknown tag instead reports the allowed tag values in its message, with an empty `errors` array.
  • Is it safe to log Zod 4 issues as they are?
    Mostly, by default: `input` is dropped from each issue, so submitted values are not echoed. Messages can still interpolate rule parameters, such as a regex pattern or the allowed enum values. Turning on `reportInput` puts the raw values back into every issue, so keep it out of production logging.

  • A ZodError reports only the first failure it meets.
  • A missing required field gets its own required issue code.
  • The issue path is a dotted string such as address.zip.
  • Every issue includes the raw input value by default.
  • Program logic should match on the message text.
  • error.errors still lists the issues, as it did in Zod 3.

Assumes Zod 4; Zod 4 merged Zod 3's invalid_enum_value and invalid_literal codes into invalid_value and folded invalid_date into invalid_type.

open as a page

In Zod 4, how do z.flattenError and z.treeifyError turn a ZodError into field messages for a sign-up form, and when does each fit?

level: middleimportance: must knowfreq 58%

basics

~20 s

z.flattenError returns formErrors for root-level issues and fieldErrors keyed by each issue's first path segment, which suits a flat form. z.treeifyError returns a nested errors/properties/items tree mirroring the schema, which suits nested objects and arrays.

open as a page

In Zod 4, how does the error param set custom messages, and which Zod 3 options (message, errorMap, required_error, invalid_type_error) did it replace?

level: middleimportance: should knowfreq 48%

basics

~20 s

Zod 4 takes one error param on schemas and checks: a string, or a function of the issue returning a message or undefined to defer. It replaces errorMap, deprecates message, and drops required_error and invalid_type_error.

open as a page

In Zod 4, z.string("Username is required").min(3) reports "Username is required" for "ab", and the error map passed to safeParse is ignored. Why?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Zod 4 picks the most specific message: check-level, then schema-level, then the per-parse map, then the global customError, then the locale. A schema-level string covers its own checks that lack a message, and outranks the per-parse map.

open as a page

In Zod 4, how should a command-line tool print a config-file validation failure, and why not print the ZodError's message property?

level: middleimportance: nice to knowfreq 24%

basics

~20 s

Pass 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.

open as a page

In Zod 4, why is calling z.config(z.locales.fr()) inside a request handler a fragile way to localise validation messages per user, and what would you do instead?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

z.config writes one process-wide config, so a per-request locale leaks into other requests and can race with async parses. Instead pass a per-parse error map for the user's language, or translate issue codes at render time.

open as a page