Node Custom Exception Utility
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
-
TypeError: Class constructor CustomError cannot be invoked without 'new'
cause Attempting to call `CustomError` or a derived class as a function instead of instantiating it with `new`.fixAlways create instances of `CustomError` or its derivatives using `new`, e.g., `throw new CustomError('message');`. -
MyCustomError is not an instance of CustomError
cause This typically occurs in transpiled environments where the prototype chain is not correctly re-established for custom error classes, preventing `instanceof` from working as expected.fixEnsure `Object.setPrototypeOf(this, MyCustomError.prototype);` is called in your custom error's constructor after `super()`.
Warnings
- breaking As the package is at version 0.1.2, its API is considered unstable. Minor or patch releases may introduce breaking changes without prior deprecation warnings. Users should lock package versions and review changes upon upgrade.
- gotcha When extending `CustomError` in a transpiled environment (e.g., Babel, TypeScript targeting ES5/ES2015), you must explicitly call `Object.setPrototypeOf(this, MyCustomError.prototype)` in the constructor after `super()` to ensure `instanceof` checks work correctly.
- gotcha Forgetting to set `this.name` in your custom error class constructor will result in the error name defaulting to 'CustomError' or 'Error' instead of your specific class name.
Install
-
npm install custom-exception -
yarn add custom-exception -
pnpm add custom-exception
Imports
- CustomError
const { CustomError } = require('custom-exception');import { CustomError } from 'custom-exception'; - CustomError
class MyError extends Error { /* ... */ } // Misses custom-exception's featuresclass MyError extends CustomError { /* ... */ }
Quickstart
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}`);
}
}