Sub topic 6
Reading and Reporting Validation Errors
Assume you know basic TypeScript, JavaScript objects, JSON, npm imports, and try/catch. This chapter focuses on turning Zod validation failures into useful messages for logs, APIs, and forms.
What a Zod error contains
When parsing fails, Zod creates a ZodError. Its issues property contains one entry for each validation problem. Each issue commonly includes:
path: an array locating the bad value.message: a human-readable explanation.code: the kind of validation failure.- Details such as
expected,received,minimum, ormaximum, depending on the check.
For example, a path of ["profile", "age"] points to profile.age. An empty path means the problem applies to the whole value rather than to one field.
Choosing `parse` or `safeParse`
Use parse when invalid input is exceptional and your surrounding code already handles exceptions. It returns the parsed value or throws an error.
Use safeParse when invalid input is an expected result, such as a form submission or an HTTP request. It returns an object with either success: true and data, or success: false and error.
import { z } from "zod";
const User = z.object({
name: z.string().min(1, "Name is required"),
age: z.number().int().min(18, "You must be at least 18"),
address: z.object({
city: z.string().min(1, "City is required"),
}),
});
const input: unknown = {
name: "",
age: 16,
address: { city: "" },
};
const result = User.safeParse(input);
if (result.success) {
console.log(`Accepted ${result.data.name}`);
} else {
for (const issue of result.error.issues) {
const field = issue.path.length > 0 ? issue.path.join(".") : "value";
console.error(`${field}: ${issue.message}`);
}
}The output identifies each failed field:
name: Name is required
age: You must be at least 18
address.city: City is requiredTypeScript narrows result after checking result.success. In the success branch, result.data has the type inferred from the schema. In the failure branch, result.error is available.
Reporting errors at an API boundary
An API should usually avoid returning internal exception details or a stack trace. Instead, convert issues into a stable response shape.
type FieldError = {
field: string;
message: string;
};
function toFieldErrors(error: z.ZodError): FieldError[] {
return error.issues.map((issue) => ({
field: issue.path.length === 0 ? "_root" : issue.path.join("."),
message: issue.message,
}));
}A client can use field to display the message beside the matching form control. Keep the original issues object for server logs when you need diagnostic details.
Error paths for arrays and cross-field rules
Array paths include numeric indexes. For example, ["items", 2, "sku"] identifies items[2].sku. Converting every path with join(".") produces items.2.sku, which is adequate for logs but may need custom formatting for a user interface.
A schema-level rule can produce an issue with an empty path. When using refine, set path to attach the message to a particular field when appropriate.
Exercise
Why is safeParse usually preferable for validating an HTTP request body?
Show answer
Invalid request data is an expected outcome, so safeParse lets the handler inspect error.issues and return a controlled client response instead of using exceptions for normal control flow.