fromZodError

fromZodError is a strict, type-safe utility that converts a guaranteed Zod Error into a ValidationError.

Signature

function fromZodError(
  zodError: ZodError,
  options?: FromZodErrorOptions
): ValidationError

Description

This function takes a collection of Zod issues (specifically a ZodError returned from a Zod schema validation) and formats them into a single, cohesive, readable string.

The Runtime Check (Important)

To prevent developers from accidentally passing generic Javascript errors into a function designed specifically for Zod issues, fromZodError performs a strict runtime check using the isZodErrorLike heuristic.

If you pass a native Error, TypeError, or a string into fromZodError, it will immediately throw a new TypeError with the message:

"Invalid zodError param; expected instance of ZodError. Did you mean to use the \"fromError\" method instead?"

Because of this strictness, you should only use fromZodError when you have previously checked the type of the error, or when you are using Zod's safeParse method which statically guarantees the error type.

Arguments

  • zodError (ZodError): The Zod Error instance to parse.
  • options (FromZodErrorOptions, optional): Formatting options to customize how the final string is built. You can pass options like maxIssuesInMessage, issueSeparator, includePath, etc. Alternatively, you can pass a custom { messageBuilder: ... } object.

Examples

Because safeParse is type-safe and doesn't throw, we know result.error is definitely a ZodError.

import { z as zod } from 'zod';
import { fromZodError } from 'zod-validation-error';

const schema = zod.object({ name: zod.string() });
const result = schema.safeParse({ name: 123 });

if (!result.success) {
  // Safe to use fromZodError because result.error is typed as ZodError
  const validationError = fromZodError(result.error, {
    prefix: 'Oops',
  });
  console.log(validationError.message);
  // "Oops: Expected string, received number at \"name\""
}

Usage in a Type-Guarded Try/Catch

If you prefer throwing (.parse()), you must guard the catch block before using fromZodError.

import { z as zod } from 'zod';
import { fromZodError, isZodErrorLike, fromError } from 'zod-validation-error';

const schema = zod.object({ name: zod.string() });

try {
  schema.parse({ name: 123 });
} catch (err) {
  if (isZodErrorLike(err)) {
    // It is safe to use fromZodError here
    const validationError = fromZodError(err);
  } else {
    // It was some other error, use the generic fromError
    const fallbackError = fromError(err);
  }
}

(Note: As seen above, using fromError() unconditionally is often much cleaner and requires less code than explicitly guarding and calling fromZodError).