ValidationError
The ValidationError class is the primary error type exposed by this library. It extends the native JavaScript Error object, meaning it behaves predictably across all JavaScript environments, logging tools, and Application Performance Monitoring (APM) services.
Constructor
new ValidationError(message?: string, options?: ErrorOptions)
Arguments
message(string, optional): The user-friendly, formatted error message.options(ErrorOptions, optional): Follows the standard ECMAScript standard for error options.options.cause(unknown): The original underlying error that triggered this validation failure. If you pass aZodError(or aZodRealError/$ZodErrordepending on Zod versions) into thecauseproperty, its internal issues will be automatically extracted.
Properties
When you catch or interact with a ValidationError, you have access to the following properties:
name: Strictly and always set to the string literal'ZodValidationError'. This is crucial for heuristic type-checking across different environments.message: The constructed string explaining the error (e.g.,"Validation error: Expected string, received number").details: An array of Zod issues (Array<zod.$ZodIssue>).- Why this matters: Even though this library's main job is creating a flat string message, it preserves the
detailsarray. If you need to map errors to specific fields in a UI (like underlining a specific input box in red), you still have the exact path and error code available in this array.
- Why this matters: Even though this library's main job is creating a flat string message, it preserves the
Methods
toString()
Overrides the default Error.prototype.toString(). It returns the message directly, avoiding the prepended Error: text that JavaScript usually adds, making it cleaner for immediate UI injection.
const err = new ValidationError('Invalid input');
console.log(err.toString()); // Outputs: "Invalid input"
Examples
Throwing a Custom Validation Error
You are not required to use Zod to utilize this class. You can throw it manually for custom business logic.
import { ValidationError } from 'zod-validation-error';
function validateAge(age: number) {
if (age < 18) {
throw new ValidationError('User must be at least 18 years old');
}
}
Instantiating with a Zod Cause
When integrating with Zod manually (though usually you would use fromError), you pass the Zod error as the cause.
import { z as zod } from 'zod';
import { ValidationError } from 'zod-validation-error';
const schema = zod.object({ email: zod.email() });
const result = schema.safeParse({ email: 'not-an-email' });
if (!result.success) {
const error = new ValidationError('Email format is invalid', {
cause: result.error // Passes the ZodError
});
console.log(error.details);
// Outputs the Zod issues array: [{ code: 'invalid_format', path: ['email'], ... }]
}