http-custom-errors
raw JSON → 8.0.0 verified Sat Apr 25 auth: no javascript
Custom error classes for all HTTP status codes (4xx and 5xx) in Node.js. Current stable version is 8.0.0, released periodically with low churn. Unlike generic error packages, it provides individual constructors for each status code (e.g., NotFoundError, ForbiddenError) and a factory function createHTTPError(code) that returns the correct error class by numeric status. Errors have code and status properties matching the HTTP status. This library is designed for use with Express.js error-handling middleware. It supports CommonJS only and has no runtime dependencies.
Common errors
error TypeError: HTTPErrors.createHTTPError is not a function ↓
cause Importing the package with ES module syntax (import) returns an empty object in Node.js CommonJS interop.
fix
Use const HTTPErrors = require('http-custom-errors');
error Error: Cannot find module 'http-custom-errors' ↓
cause Package not installed or located in node_modules.
fix
Run 'npm install http-custom-errors' and ensure the file is in the same project.
error HTTPErrors.NotFoundError is not a constructor ↓
cause Attempting to instantiate an error without the 'new' keyword.
fix
Use new HTTPErrors.NotFoundError(message);
Warnings
gotcha The library is CommonJS-only; ES module imports will fail at runtime. ↓
fix Use require() instead of import.
gotcha Error instances have statusCode and code properties both set to the HTTP status number. ↓
fix Use err.code or err.statusCode interchangeably.
deprecated createHTTPError with invalid/unknown status codes returns a generic Error instead of throwing. ↓
fix Wrap calls in try/catch or validate the code before calling.
Install
npm install http-custom-errors yarn add http-custom-errors pnpm add http-custom-errors Imports
- HTTPErrors wrong
import HTTPErrors from 'http-custom-errors'correctconst HTTPErrors = require('http-custom-errors') - NotFoundError wrong
const NotFoundError = require('http-custom-errors').NotFoundErrorcorrectconst { NotFoundError } = require('http-custom-errors') - createHTTPError wrong
const createHTTPError = require('http-custom-errors').createHTTPErrorcorrectconst { createHTTPError } = require('http-custom-errors')
Quickstart
const HTTPErrors = require('http-custom-errors');
try {
throw new HTTPErrors.NotFoundError('/missing');
} catch (err) {
console.log(err.statusCode); // 404
console.log(err.message); // Not Found
console.log(err.code); // 404
}
const err = HTTPErrors.createHTTPError(500);
console.log(err.name); // InternalServerError
console.log(err.statusCode); // 500