Course contentsShow
← JavaScript
Lesson 2642 of 2,72353. Type Safety Without TypeScriptFree lesson

Error Handling and Custom Messages

Extract validation errors, customize error messages, and integrate Zod errors into your app.

Error Handling and Custom Messages

You'll learn how to extract meaningful validation errors from Zod and customize error messages to create better user experiences.

When Zod validation fails, it doesn't just throw a generic error—it provides detailed information about what went wrong and where. Understanding how to extract and format these errors is crucial for building production-ready applications.

Understanding Zod Errors

When you use .parse() and validation fails, Zod throws a ZodError object. This error contains an issues array with detailed information about each validation failure. When you use .safeParse(), errors are returned in the error property without throwing.

const schema = z.object({
  email: z.string().email(),
  age: z.number().min(18)
});

const result = schema.safeParse({ email: "invalid", age: 15 });

if (!result.success) {
  console.log(result.error.issues);
  // Each issue contains: path, message, code
}

Customizing Error Messages

You can provide custom messages directly in your schema using the second argument to most Zod methods:

const schema = z.object({
  email: z.string().email({ message: "Please enter a valid email address" }),
  age: z.number().min(18, { message: "You must be at least 18 years old" })
});

Formatting Errors for Your App

You can transform Zod's error structure into a format that matches your application needs:

const result = schema.safeParse(data);

if (!result.success) {
  const fieldErrors = {};
  result.error.issues.forEach(issue => {
    const field = issue.path[0];
    fieldErrors[field] = issue.message;
  });
  // Now you have { email: "...", age: "..." }
}

Key Takeaway: Zod provides structured error information through the issues array, and you can customize messages at the schema level or transform error objects to match your application's error-handling patterns.