Fejl Error Utility

4.0.1 · active · verified Tue Apr 21

Fejl is a JavaScript and TypeScript utility library designed to streamline the creation and management of custom error classes in Node.js applications. Currently in its stable v4.0.1 release, Fejl offers a predictable release cadence with major versions typically introducing significant changes like ESM support or Node.js version bumps. Its core functionality revolves around `MakeErrorClass`, which allows developers to define custom error types with default messages and properties, drastically reducing boilerplate compared to native `Error` extension. Key differentiators include static `assert` and `makeAssert` methods for concise conditional error throwing, and a collection of pre-defined HTTP error classes. Fejl aims to improve code readability and maintainability by centralizing error definitions and providing convenient assertion patterns.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating a custom error class with default properties, handling it, and using static assertion methods with built-in HTTP errors.

import { MakeErrorClass, NotFound } from 'fejl';

// 1. Create a custom error class with a default message and properties
class InvalidConfigError extends MakeErrorClass(
  'The configuration file is invalid',
  { infoUrl: 'https://example.com/error-info' }
) {}

// 2. Demonstrate throwing and catching a custom error
try {
  throw new InvalidConfigError('Custom message ignored');
} catch (err) {
  console.log(`Error Name: ${err.name}`); // InvalidConfigError
  console.log(`Error Message: ${err.message}`); // The configuration file is invalid (default message is used)
  console.log(`Error Info URL: ${err.infoUrl}`); // https://example.com/error-info
  console.log(`Is instance of InvalidConfigError? ${err instanceof InvalidConfigError}`); // true
}

// 3. Use a built-in HTTP error with static assertion
class UserNotFoundError extends NotFound {}

function getUserById(id) {
  const user = id === 1 ? { id: 1, name: 'Alice' } : null;
  // Use static assert to throw if 'user' is falsy
  UserNotFoundError.assert(user, `User with ID ${id} not found.`);
  return user;
}

try {
  getUserById(2);
} catch (err) {
  console.log(`\nHTTP Error Name: ${err.name}`); // NotFound
  console.log(`HTTP Error Message: ${err.message}`); // User with ID 2 not found.
  console.log(`HTTP Status Code: ${err.statusCode}`); // 404
}

view raw JSON →