HTTP Errors Enhanced
`http-errors-enhanced` is a JavaScript and TypeScript library for creating standardized HTTP error objects with additional properties. It extends the native `Error` class, providing a base `HttpError` class, specific error classes (e.g., `NotFoundError`), and a `createError` factory function. Currently stable at version 4.0.2, the library typically sees patch and minor updates for bug fixes and dependency upgrades, with major versions primarily dropping support for older Node.js runtimes. Key differentiators include its explicit support for attaching arbitrary additional properties to errors, automatic HTTP status code descriptions, `Error.cause` support since v3, and an `expose` property for controlling client visibility. It is designed to be framework-agnostic, allowing for consistent error handling across different environments. The library is ESM-only and ships with TypeScript types.
Common errors
-
Error [ERR_REQUIRE_ESM]: require() of ES Module .../node_modules/http-errors-enhanced/dist/index.js from ... not supported. Instead change the require of index.js to a dynamic import() which is available in all CommonJS modules.
cause Attempting to import `http-errors-enhanced` using CommonJS `require()` syntax in a Node.js environment.fixConvert your module to an ES Module (by setting `"type": "module"` in `package.json` or using `.mjs` extension) and use `import { ... } from 'http-errors-enhanced';` or use a dynamic import `import('http-errors-enhanced')`. -
The package 'http-errors-enhanced' requires Node.js version >= 22.21.0. The current Node.js version is v20.x.x.
cause The installed version of `http-errors-enhanced` (v4.x.x) is not compatible with your current Node.js runtime.fixUpgrade your Node.js runtime to version 22.21.0 or higher. Use `nvm install 22 && nvm use 22` to switch Node.js versions if you have `nvm` installed. -
TypeError: HttpError is not a constructor
cause This error typically occurs when trying to call `HttpError` as a function or without the `new` keyword, or if the import path is incorrect/module is not properly loaded.fixEnsure you are using the `new` keyword when instantiating `HttpError` (e.g., `new HttpError(...)`) or use the `createError` factory function (e.g., `createError(...)`). Verify your `import` statement is correct.
Warnings
- breaking Version 4.0.0 of `http-errors-enhanced` dropped support for Node.js 20. The package now requires Node.js version >= 22.21.0.
- breaking Version 3.0.0 of `http-errors-enhanced` dropped support for Node.js 18. This version requires Node.js 20 or higher.
- gotcha When constructing an `HttpError` or using `createError`, invalid HTTP status codes (outside 400-599) or unrecognized string identifiers will default the error's status to 500 (Internal Server Error).
- gotcha The `properties` object passed to error constructors or `createError` will ignore attempts to overwrite certain reserved error properties like `code`, `message`, `stack`, `expose`, and `headers` if they already exist on the error object. Only non-reserved or new properties will be added.
Install
-
npm install http-errors-enhanced -
yarn add http-errors-enhanced -
pnpm add http-errors-enhanced
Imports
- HttpError
const { HttpError } = require('http-errors-enhanced')import { HttpError } from 'http-errors-enhanced' - NotFoundError
const { NotFoundError } = require('http-errors-enhanced')import { NotFoundError } from 'http-errors-enhanced' - createError
const { createError } = require('http-errors-enhanced')import { createError } from 'http-errors-enhanced'
Quickstart
import { HttpError, NotFoundError, createError } from 'http-errors-enhanced';
// Demonstrate creating a generic HTTP error with a numeric status code and custom properties
const genericError = new HttpError(400, 'Invalid request parameters.', {
requestId: 'abc-123',
details: 'Missing required field: userId'
});
console.log('Generic Error:', genericError.status, genericError.message, genericError.requestId);
// Demonstrate creating a specific HTTP error by its class name, with custom message and properties
const notFoundError = new NotFoundError('Resource /users/123 not found.', {
resource: '/users/123',
userId: 'non-existent'
});
console.log('Not Found Error:', notFoundError.status, notFoundError.error, notFoundError.resource);
// Demonstrate using the createError factory function with a string identifier and properties
const badGatewayError = createError('BadGateway', {
upstreamService: 'payment-gateway',
responseCode: 502,
message: 'Failed to connect to payment service.'
});
console.log('Bad Gateway Error:', badGatewayError.status, badGatewayError.errorPhrase, badGatewayError.upstreamService);
// Example of accessing built-in properties like isClientError
if (genericError.isClientError) {
console.log('This is a client error and can potentially be exposed to the client.');
}
// You can also add a cause to errors (supported since v3.0.0)
const originalDbError = new Error('Database connection failed due to network timeout.');
const internalServerError = new HttpError(500, 'An unexpected error occurred processing your request.', {
transactionId: 'xyz-456'
}, { cause: originalDbError });
console.log('Internal Server Error with cause:', internalServerError.cause?.message);