Error Comparison and Information Utility

2.1.3 · active · verified Sun Apr 19

check-error is a JavaScript utility library designed for robust error inspection and comparison in both Node.js and browser environments. Currently at stable version 2.1.3, it provides functions to retrieve error information, such as constructor names and messages, and to determine compatibility between errors based on their instance, constructor, or message content. It is a foundational utility often employed within testing frameworks, particularly Chai, for asserting error conditions. Since version 2.0.0, it is an ESM-only module, requiring modern JavaScript environments (Node.js 16+, Firefox 102+, Chromium Edge+). Releases are infrequent, focusing on maintenance and modernizing the codebase to align with current JavaScript standards. Its key differentiator is providing a standardized set of primitives for error interrogation, abstracted away from environment-specific quirks, which simplifies error handling logic across different contexts. This ensures consistent behavior when dealing with various types of errors and their properties.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates catching different error types and using `check-error` to inspect their constructor names, messages, and compatibility with other error types.

import * as checkError from 'check-error';

class CustomError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'CustomError';
  }
}

function potentiallyFailingOperation(shouldThrow: boolean, type: string = 'TypeError'): void {
  if (shouldThrow) {
    if (type === 'CustomError') {
      throw new CustomError('Something went wrong with custom logic.');
    } else {
      throw new TypeError('Invalid data format received.');
    }
  }
}

try {
  potentiallyFailingOperation(true);
} catch (e: unknown) {
  if (e instanceof Error) {
    console.log(`Caught error: ${e.message}`);
    console.log(`Constructor name: ${checkError.getConstructorName(e)}`);
    console.log(`Is compatible with TypeError? ${checkError.compatibleConstructor(e, TypeError)}`);
    console.log(`Is compatible with message 'data format'? ${checkError.compatibleMessage(e, 'data format')}`);
    console.log(`Is compatible with CustomError? ${checkError.compatibleConstructor(e, CustomError)}`);
  }
}

try {
  potentiallyFailingOperation(true, 'CustomError');
} catch (e: unknown) {
  if (e instanceof Error) {
    console.log(`\nCaught another error: ${e.message}`);
    console.log(`Constructor name: ${checkError.getConstructorName(e)}`);
    console.log(`Is compatible with TypeError? ${checkError.compatibleConstructor(e, TypeError)}`);
    console.log(`Is compatible with CustomError? ${checkError.compatibleConstructor(e, CustomError)}`);
  }
}

view raw JSON →