HTTP Status Code Errors
raw JSON →throw-http-errors is a JavaScript/TypeScript library designed to streamline the creation and handling of HTTP status code-specific errors. Currently at version 4.0.1, the library provides a comprehensive set of custom error classes corresponding to most standard HTTP status codes, from client errors like `BadRequest` (400) and `Unauthorized` (401) to server errors such as `InternalServerError` (500) and `ServiceUnavailable` (503). It allows developers to instantiate these errors either by their descriptive named class (e.g., `new errors.NotFound('User not found')`) or by their numeric status code (e.g., `new errors[404]('Resource missing')`), along with optional custom messages and internal error codes, providing flexibility for different error reporting needs. The library also includes a `CreateCustomError` utility for defining unique application-specific HTTP errors. This package differentiates itself by offering a structured, type-safe approach to HTTP error propagation in modern Node.js and browser environments, shipping with full TypeScript definitions to enhance developer experience and reduce runtime errors. While a previous JavaScript-only version exists on a separate branch (pre-v4), the current major version prioritizes TypeScript and ESM, ensuring a modern and robust error handling mechanism for web applications and APIs. The project maintains a steady release cadence, with major versions typically indicating significant architectural or language-level shifts.
Common errors
error TypeError: errors is not a constructor ↓
new errors.BadRequest() or new errors[400]() to create specific HTTP error instances, or import and instantiate individual error classes like new BadRequest(). error ReferenceError: require is not defined ↓
import { BadRequest } from 'throw-http-errors'; or import * as errors from 'throw-http-errors';. error TypeError: (0 , _throw_http_errors.BadRequest) is not a constructor ↓
esModuleInterop, allowSyntheticDefaultImports) is correctly set up to handle module interop. If using TypeScript, set "esModuleInterop": true in your tsconfig.json. Always explicitly import named exports: import { BadRequest } from 'throw-http-errors';. Warnings
breaking Version 4.0.0 introduced a significant shift to a TypeScript-first, ESM-oriented codebase. Projects previously relying on CommonJS `require()` might encounter issues, especially in environments that do not transpile or bundle ESM correctly, or if explicit module specifiers are not used. ↓
gotcha The main `errors` object exported by the library (whether through CommonJS `require` or ESM namespace import) is a collection of error constructors, not a constructor itself. Attempting to instantiate `new errors()` will result in a TypeError. ↓
Install
npm install throw-http-errors yarn add throw-http-errors pnpm add throw-http-errors Imports
- BadRequest wrong
import BadRequest from 'throw-http-errors';correctimport { BadRequest } from 'throw-http-errors'; - errors wrong
const errors = require('throw-http-errors');correctimport * as errors from 'throw-http-errors'; - errors wrong
import errors from 'throw-http-errors';correctconst errors = require('throw-http-errors');
Quickstart
import { BadRequest, NotFound, InternalServerError, CreateCustomError, HttpError } from 'throw-http-errors';
// Define a custom application-specific error with a specific status code
const TooManyRequestsFromUser = CreateCustomError(429, 'TooManyRequestsFromUser', 'Too many requests from this user ID', 1002);
function simulateApiRequest(userId: string, data: any): { success: boolean; message?: string } {
try {
if (!userId) {
// Throw an error by class name
throw new BadRequest('User ID is required.', 1001);
}
if (userId === 'blocked_user') {
// Throw a custom error
throw new TooManyRequestsFromUser();
}
if (data.id === 'nonexistent') {
// Throw an error by status code number
throw new NotFound('Resource with provided ID not found.', 1003);
}
// Simulate an unexpected server error
if (Math.random() < 0.1) {
throw new InternalServerError('An unexpected database error occurred.', 5000);
}
return { success: true, message: `Request processed for user ${userId}.` };
} catch (error) {
if (error instanceof HttpError) {
console.error(`HTTP Error (${error.statusCode} - ${error.name}): ${error.message} (Code: ${error.code})`);
return { success: false, message: `Failed: ${error.message}` };
} else if (error instanceof Error) {
console.error(`Generic Error: ${error.message}`);
return { success: false, message: `An unknown error occurred: ${error.message}` };
}
throw error; // Re-throw if not an Error instance
}
}
console.log(simulateApiRequest('', { id: 'test' })); // Should throw BadRequest
console.log(simulateApiRequest('test_user', {})); // Should succeed or throw InternalServerError randomly
console.log(simulateApiRequest('blocked_user', { id: 'valid' })); // Should throw TooManyRequestsFromUser
console.log(simulateApiRequest('another_user', { id: 'nonexistent' })); // Should throw NotFound
console.log(simulateApiRequest('admin_user', { id: 'secret' })); // Should succeed or throw InternalServerError randomly