Better AJV Errors transforms standard AJV JSON Schema validation errors into beautifully formatted, human-readable error messages with syntax highlighting, line numbers, and helpful suggestions. It enhances the debugging experience for JSON Schema validation by providing contextual error messages that help developers quickly identify and fix validation issues.
npm install better-ajv-errorsimport betterAjvErrors from "better-ajv-errors";For CommonJS:
const betterAjvErrors = require("better-ajv-errors").default;
// or
const { default: betterAjvErrors } = require("better-ajv-errors");TypeScript:
import betterAjvErrors, { IInputOptions, IOutputError } from "better-ajv-errors";import Ajv from "ajv";
import betterAjvErrors from "better-ajv-errors";
// Create AJV instance
const ajv = new Ajv();
// Your schema and data
const schema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "number", minimum: 0 }
},
required: ["name"]
};
const data = { age: "25" }; // Invalid: missing name, age is string not number
// Validate with AJV
const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) {
// Get beautiful error output
const output = betterAjvErrors(schema, data, validate.errors, {
format: 'cli',
indent: 2
});
console.log(output);
}Transforms AJV validation errors into human-readable format with two output modes: CLI format for console display and structured JS format for programmatic use.
/**
* Transform AJV validation errors into formatted output
* @param schema - The JSON Schema used for validation
* @param data - The JSON payload being validated
* @param errors - Array of AJV validation errors
* @param options - Configuration options
* @returns Formatted string (CLI mode) or array of error objects (JS mode)
*/
function betterAjvErrors<S, T, Options extends IInputOptions>(
schema: S,
data: T,
errors: Array<ErrorObject>,
options?: Options
): Options extends { format: 'js' } ? Array<IOutputError> : string;
/** AJV error object structure (from ajv package) */
interface ErrorObject {
instancePath: string;
schemaPath: string;
keyword: string;
params: Record<string, any>;
message?: string;
}CLI Format Output:
When format: 'cli' (default), returns a formatted string with syntax highlighting and code frames:
ValidationError: JSON validation failed
1 | {
> 2 | "age": "25"
| ^^^^
3 | }
/age should be number
ValidationError: JSON validation failed
1 | {
2 | "age": "25"
3 | }
/ should have required property 'name'JS Format Output:
When format: 'js', returns an array of structured error objects for programmatic use:
[
{
start: { line: 2, column: 10, offset: 12 },
end: { line: 2, column: 14, offset: 16 },
error: "/age should be number",
suggestion: undefined
},
{
start: { line: 1, column: 1, offset: 0 },
error: "/ should have required property 'name'",
suggestion: undefined
}
]Options for configuring the error formatting behavior.
interface IInputOptions {
/** Output format: 'cli' for console display, 'js' for structured data */
format?: 'cli' | 'js';
/** Indentation level for JSON formatting when json option is not provided */
indent?: number | null;
/** Raw JSON string for accurate line/column positioning */
json?: string | null;
}format (default: 'cli')
'cli': Returns formatted string with syntax highlighting for console output'js': Returns array of structured error objects for programmatic useindent (default: null)
json option is not providedjson (default: null)
Structure of error objects returned when using format: 'js'.
interface IOutputError {
/** Starting position of the error in the JSON */
start: { line: number; column: number; offset: number };
/** Ending position of the error (optional, not set for required property errors) */
end?: { line: number; column: number; offset: number };
/** Human-readable error message */
error: string;
/** Helpful suggestion for fixing the error (optional, mainly for enum errors) */
suggestion?: string;
}import betterAjvErrors from "better-ajv-errors";
const schema = { type: "string" };
const data = 123;
const jsonString = `{
"value": 123,
"config": {
"debug": true
}
}`;
const ajv = new Ajv();
const validate = ajv.compile(schema);
validate(data);
// Use raw JSON for accurate positioning
const output = betterAjvErrors(schema, data, validate.errors, {
format: 'cli',
json: jsonString
});const errors = betterAjvErrors(schema, data, validate.errors, {
format: 'js'
});
errors.forEach(error => {
console.log(`Error at line ${error.start.line}: ${error.error}`);
if (error.suggestion) {
console.log(`Suggestion: ${error.suggestion}`);
}
});const output = betterAjvErrors(schema, data, validate.errors, {
format: 'cli',
indent: 2 // Pretty-print JSON with 2-space indentation
});The package relies on several key dependencies for its functionality:
Full TypeScript definitions are included with the package. The main function uses generics to preserve type relationships between input schema/data and output format.
import betterAjvErrors, { IInputOptions, IOutputError } from "better-ajv-errors";
import type { ErrorObject } from "ajv";
// Type-safe usage
const errors: IOutputError[] = betterAjvErrors(
schema,
data,
ajvErrors,
{ format: 'js' }
);