Skip to main content

ZodError Structure

When validation fails, Zod throws a ZodError that contains detailed information about all validation issues.

Basic Error Structure

The ZodError object contains:
  • issues: Array of $ZodIssue objects describing each validation failure
  • message: JSON stringified representation of all issues
  • name: Always "ZodError"

Issue Types

Zod provides different issue types for various validation failures:

Invalid Type Issue

Example:

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

The flatten() 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)

The format() 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

Don’t call .parse() on schemas with async refinements. It will throw an error. Use .parseAsync() instead.

TypeScript Type Inference

Best Practices

  1. Use safeParse in production - Returns a result object instead of throwing
  2. Flatten for forms - Use .flatten() for form validation to map errors to fields
  3. Format for nested data - Use .format() for complex nested objects
  4. Add context with params - Include params in refinements for dynamic error messages
  5. Set custom paths - Use the path option in refinements to target specific fields