or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-better-ajv-errors

JSON Schema validation error formatter that transforms AJV errors into human-readable messages with syntax highlighting

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/better-ajv-errors@2.0.x

To install, run

npx @tessl/cli install tessl/npm-better-ajv-errors@2.0.0

index.mddocs/

Better AJV Errors

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.

Package Information

  • Package Name: better-ajv-errors
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install better-ajv-errors

Core Imports

import 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";

Basic Usage

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);
}

Capabilities

Error Formatting

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
  }
]

Configuration Options

Input Options Interface

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 use

indent (default: null)

  • When provided, formats the JSON payload with specified indentation
  • Only used when json option is not provided
  • Helps with readability in error output

json (default: null)

  • Raw JSON string used for accurate line and column positioning
  • When provided, gives precise location information in code frames
  • Overrides automatic JSON stringification of the data parameter

Output Error Interface

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;
}

Usage Examples

With Custom JSON 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
});

Programmatic Error Handling

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}`);
  }
});

With Indentation

const output = betterAjvErrors(schema, data, validate.errors, {
  format: 'cli',
  indent: 2  // Pretty-print JSON with 2-space indentation
});

Error Types and Features

Smart Error Filtering

  • Prioritizes meaningful errors over redundant ones
  • Required property errors take precedence over other validation errors
  • Removes duplicate enum errors and consolidates similar issues

Enhanced Error Messages

  • Required Property Errors: Clear indication of missing required fields
  • Type Errors: Specific information about expected vs actual types
  • Enum Errors: Lists allowed values and provides suggestions for typos
  • Additional Property Errors: Identifies unexpected properties in objects

Syntax Highlighting

  • Uses Babel's code frame for syntax-highlighted error display
  • Provides context around error locations
  • Shows line numbers and column positions
  • Highlights specific problem areas with carets and underlines

Dependencies

The package relies on several key dependencies for its functionality:

  • @babel/code-frame: Provides syntax-highlighted code frames
  • @humanwhocodes/momoa: JSON AST parsing for accurate positioning
  • chalk: Terminal color formatting
  • jsonpointer: JSON pointer path utilities
  • leven: String similarity calculations for suggestions

Peer Dependencies

  • ajv (versions 4.11.8 - 8): JSON Schema validator that generates the errors to be formatted

TypeScript Support

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' }
);