Node Custom Exception Utility

0.1.2 · active · verified Sun Apr 19

The `custom-exception` package, currently at version 0.1.2, provides a foundational utility for creating custom error classes within Node.js applications. It aims to simplify the process of defining structured, extensible error types beyond the standard JavaScript `Error` object. While still in early development, as indicated by its low version number, it offers a mechanism to differentiate application-specific errors programmatically. Its release cadence is likely irregular, given its nascent stage. Key differentiators typically include boilerplate reduction for custom error inheritance, properties like status codes, and improved stack trace handling, though specifics depend on the full API. Users should anticipate potential API changes as the library evolves towards a stable major release.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates defining a custom error by extending `CustomError`, adding custom properties, and catching it with `instanceof` checks.

import { CustomError } from 'custom-exception';

/**
 * Define a custom application-specific error by extending CustomError.
 * This allows for adding custom properties like 'code' or 'data'.
 */
class NotFoundError extends CustomError {
  constructor(message: string, resourceId?: string) {
    super(message);
    this.name = 'NotFoundError';
    this.statusCode = 404; // Custom property
    this.resourceId = resourceId; // Custom property
    // Restore prototype chain for 'instanceof' checks in transpiled environments
    Object.setPrototypeOf(this, NotFoundError.prototype);
  }
}

/**
 * A function that might throw our custom error.
 */
function getUser(userId: string) {
  if (userId === 'nonexistent') {
    throw new NotFoundError(`User with ID '${userId}' not found.`, userId);
  }
  return { id: userId, name: `User ${userId}` };
}

try {
  const user = getUser('nonexistent');
  console.log(user);
} catch (error) {
  if (error instanceof NotFoundError) {
    console.error(`Error: ${error.name} - ${error.message} (Status: ${error.statusCode}, Resource: ${error.resourceId})`);
  } else if (error instanceof CustomError) {
    console.error(`Caught a generic CustomError: ${error.name} - ${error.message}`);
  } else if (error instanceof Error) {
    console.error(`Caught a standard Error: ${error.name} - ${error.message}`);
  }
}

view raw JSON →