Handling errors with ZodError in Zod
parse returns the validated value or throws a ZodError. You can catch that error and list which fields failed.
How it works
- Parse valid data.
Player.parse()is called with a valid object. The code prints the value it returns. [1] - Catch the thrown error. The invalid object is parsed inside
try/catch. The code checkserr instanceof z.ZodErrorbefore reading the error. [1] - Print each issue. The README's example shows entries in
err.issueswith fields such ascode,pathandmessage. The code loops overerr.issuesand prints those three fields for each entry. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import * as z from "zod";
const Player = z.object({
username: z.string(),
xp: z.number(),
});
// valid input: parse returns the value
const ok = Player.parse({ username: "billie", xp: 100 });
console.log("parsed:", JSON.stringify(ok));
// invalid input: parse throws
try {
Player.parse({ username: 42, xp: "100" });
console.log("no error thrown");
} catch (err) {
if (err instanceof z.ZodError) {
console.log("ZodError with", err.issues.length, "issues:");
for (const issue of err.issues) {
console.log(" path:", issue.path.join("."));
console.log(" code:", issue.code);
console.log(" message:", issue.message);
}
} else {
console.log("other error:", String(err));
}
}
Change the invalid object so only one field is wrong and watch the issue list shrink. Code written by AgentGid [1].
Change the invalid object so only one field is wrong and watch the issue list shrink. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with zod 4.6.6. Needs WebGL.
More Zod examples
String formats in Zod: email, UUID, phone, datetime String validation in Zod Type coercion in Zod Literal values in Zod
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.