ZodError Structure
When validation fails, Zod throws aZodError that contains detailed information about all validation issues.
Basic Error Structure
ZodError object contains:
issues: Array of$ZodIssueobjects describing each validation failuremessage: JSON stringified representation of all issuesname: Always"ZodError"
Issue Types
Zod provides different issue types for various validation failures:Invalid Type Issue
Too Small/Too Big Issues
Invalid Format Issue
Custom Issue
Error Formatting
Zod provides multiple ways to format errors for different use cases.Flattened Errors
Theflatten() method groups errors into form-level and field-level errors:
Custom Flatten Mapper
You can provide a custom mapper function to transform issues:Formatted Errors (Tree Structure)
Theformat() method creates a nested tree structure matching your schema:
Root Level Formatting
Custom Error Messages
String Parameter
The simplest way to customize error messages:Message Object
Refinement with Custom Path
Refinement with Params
Use
params to pass additional metadata to error maps for dynamic message generation.Error Utilities
Adding Issues
Checking Empty Errors
TypeScript Type Inference
Best Practices
- Use
safeParsein production - Returns a result object instead of throwing - Flatten for forms - Use
.flatten()for form validation to map errors to fields - Format for nested data - Use
.format()for complex nested objects - Add context with params - Include
paramsin refinements for dynamic error messages - Set custom paths - Use the
pathoption in refinements to target specific fields