{"id":17978,"library":"throw-http-errors","title":"HTTP Status Code Errors","description":"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.","status":"active","version":"4.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/eldimious/throw-error","tags":["javascript","throw","errors","throw errors","http errors","typescript"],"install":[{"cmd":"npm install throw-http-errors","lang":"bash","label":"npm"},{"cmd":"yarn add throw-http-errors","lang":"bash","label":"yarn"},{"cmd":"pnpm add throw-http-errors","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This is the preferred way to import individual HTTP error constructors in modern ESM projects and TypeScript.","wrong":"import BadRequest from 'throw-http-errors';","symbol":"BadRequest","correct":"import { BadRequest } from 'throw-http-errors';"},{"note":"Use this namespace import to access all error constructors (e.g., `errors.NotFound` or `errors[404]`) in ESM projects. The CommonJS `require` pattern is typically for older Node.js environments.","wrong":"const errors = require('throw-http-errors');","symbol":"errors","correct":"import * as errors from 'throw-http-errors';"},{"note":"This CommonJS `require` pattern is supported for legacy Node.js projects, but for modern ESM, `import * as errors from 'throw-http-errors';` is recommended, especially in v4+.","wrong":"import errors from 'throw-http-errors';","symbol":"errors","correct":"const errors = require('throw-http-errors');"}],"quickstart":{"code":"import { BadRequest, NotFound, InternalServerError, CreateCustomError, HttpError } from 'throw-http-errors';\n\n// Define a custom application-specific error with a specific status code\nconst TooManyRequestsFromUser = CreateCustomError(429, 'TooManyRequestsFromUser', 'Too many requests from this user ID', 1002);\n\nfunction simulateApiRequest(userId: string, data: any): { success: boolean; message?: string } {\n  try {\n    if (!userId) {\n      // Throw an error by class name\n      throw new BadRequest('User ID is required.', 1001);\n    }\n    if (userId === 'blocked_user') {\n      // Throw a custom error\n      throw new TooManyRequestsFromUser();\n    }\n    if (data.id === 'nonexistent') {\n      // Throw an error by status code number\n      throw new NotFound('Resource with provided ID not found.', 1003);\n    }\n\n    // Simulate an unexpected server error\n    if (Math.random() < 0.1) {\n      throw new InternalServerError('An unexpected database error occurred.', 5000);\n    }\n\n    return { success: true, message: `Request processed for user ${userId}.` };\n  } catch (error) {\n    if (error instanceof HttpError) {\n      console.error(`HTTP Error (${error.statusCode} - ${error.name}): ${error.message} (Code: ${error.code})`);\n      return { success: false, message: `Failed: ${error.message}` };\n    } else if (error instanceof Error) {\n      console.error(`Generic Error: ${error.message}`);\n      return { success: false, message: `An unknown error occurred: ${error.message}` };\n    }\n    throw error; // Re-throw if not an Error instance\n  }\n}\n\nconsole.log(simulateApiRequest('', { id: 'test' })); // Should throw BadRequest\nconsole.log(simulateApiRequest('test_user', {})); // Should succeed or throw InternalServerError randomly\nconsole.log(simulateApiRequest('blocked_user', { id: 'valid' })); // Should throw TooManyRequestsFromUser\nconsole.log(simulateApiRequest('another_user', { id: 'nonexistent' })); // Should throw NotFound\nconsole.log(simulateApiRequest('admin_user', { id: 'secret' })); // Should succeed or throw InternalServerError randomly\n","lang":"typescript","description":"Demonstrates how to create and catch various HTTP-specific errors, including custom ones, within a simulated API request function. It shows instantiation by named classes and how to handle them polymorphically using `instanceof HttpError`."},"warnings":[{"fix":"For ESM projects, use `import { ErrorName } from 'throw-http-errors';` or `import * as errors from 'throw-http-errors';`. For CommonJS projects, ensure your build setup correctly handles ESM modules, or consider sticking to a pre-v4 version if a full migration to ESM imports is not feasible.","message":"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.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Always instantiate specific error classes, e.g., `new errors.NotFound()` or `new errors[404]()`, or import them individually as named exports like `new NotFound()`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Use `new errors.BadRequest()` or `new errors[400]()` to create specific HTTP error instances, or import and instantiate individual error classes like `new BadRequest()`.","cause":"Attempting to instantiate the `errors` object directly instead of a specific HTTP error class.","error":"TypeError: errors is not a constructor"},{"fix":"Migrate your imports to ESM syntax: `import { BadRequest } from 'throw-http-errors';` or `import * as errors from 'throw-http-errors';`.","cause":"Attempting to use CommonJS `require` syntax in an ECMAScript Module (ESM) project, especially in Node.js environments configured for ESM (`\"type\": \"module\"` in `package.json`) or in modern browsers.","error":"ReferenceError: require is not defined"},{"fix":"Ensure your bundler (e.g., Webpack, Rollup, Parcel) or TypeScript configuration (`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';`.","cause":"This often occurs in bundled or transpiled projects when there's a mismatch between how CommonJS modules are imported into an ESM context, or incorrect default/named export handling during bundling.","error":"TypeError: (0 , _throw_http_errors.BadRequest) is not a constructor"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}