fromError

fromError is the safest, most forgiving, and most commonly used utility function in the library. It takes any unknown error and guarantees the return of a well-formatted ValidationError.

Signature

function fromError(
  err: unknown,
  options?: FromZodErrorOptions
): ValidationError

Description & Internal Mechanics

When writing a standard try/catch block in TypeScript, the caught err object is of type unknown. You don't know if it's a ZodError, a TypeError, a SyntaxError, or even a thrown string.

fromError safely inspects the unknown payload using the isZodErrorLike heuristic:

  1. If it IS a Zod Error: It leverages the internal MessageBuilder to aggregate the array of issues into a clean, human-readable string, applies your configuration options, and returns a ValidationError.
  2. If it IS NOT a Zod Error, but is an Error instance: It retains the original error's .message and wraps it in a ValidationError.
  3. If it is a primitive (string, null, etc): It safely wraps it, falling back to an 'Unknown error' message.

Because it never throws on bad inputs, fromError is the recommended method for all generic catch blocks.

Arguments

  • err (unknown): The error payload to be converted.
  • options (FromZodErrorOptions, optional): Configuration options for formatting the message. You can pass a partial MessageBuilderOptions object (like issueSeparator, prefix, includePath), OR you can pass a fully instantiated MessageBuilder function via { messageBuilder: myCustomBuilder }.

Examples

Handling Standard Zod Validations

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

const schema = zod.string().email();

try {
  schema.parse('invalid-email-string');
} catch (err) {
  const vError = fromError(err, {
    prefix: 'Data format issue',
    issueSeparator: ' ~ '
  });

  console.log(vError.message);
  // "Data format issue: Invalid email address"
}

Gracefully Handling Unexpected JavaScript Errors

If the code inside the try block throws a native TypeError (e.g., trying to access a property of undefined), fromError handles it gracefully without crashing.

import { fromError } from 'zod-validation-error';

try {
  const x = undefined;
  console.log(x.someProperty); // Throws TypeError
} catch (err) {
  const vError = fromError(err);

  console.log(vError.message);
  // "Cannot read properties of undefined (reading 'someProperty')"

  console.log(vError.name);
  // "ZodValidationError"
}

Best Practices

  • Always prefer fromError over fromZodError when interacting with data directly from an API endpoint, as a malicious payload could theoretically trigger non-Zod exceptions (like JSON parsing errors) before Zod even touches the data. Using fromError ensures your error handling pipeline won't break.