{"id":17383,"library":"throwable-http-errors","title":"Throwable HTTP Errors","description":"Throwable HTTP Errors is a Node.js library designed to provide a comprehensive set of strongly-typed HTTP exception classes (e.g., BadRequest, NotFound, InternalServerError) for use in API development. The library, currently at stable version 2.0.3, aims to streamline error handling by integrating naturally with modern JavaScript's `async/await` syntax and `try/catch` blocks. It differentiates itself from older patterns that relied solely on `next(error)` callbacks by promoting the throwing of specific HTTP-related errors, which can then be caught and handled with standard error flow control. This approach enhances code readability and consistency in handling HTTP-specific error conditions across an application. While a specific release cadence isn't published, the current version was released over a year ago, indicating a mature and relatively stable project. The package also ships with TypeScript type definitions, making it suitable for modern TypeScript projects.","status":"active","version":"2.0.3","language":"javascript","source_language":"en","source_url":"https://github.com/fatmatto/throwable-http-errors","tags":["javascript","es6","error","http","typescript"],"install":[{"cmd":"npm install throwable-http-errors","lang":"bash","label":"npm"},{"cmd":"yarn add throwable-http-errors","lang":"bash","label":"yarn"},{"cmd":"pnpm add throwable-http-errors","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"For CommonJS environments, the main export is an object containing all error classes.","wrong":"import Errors from 'throwable-http-errors';","symbol":"AllErrors (CommonJS)","correct":"const Errors = require('throwable-http-errors');"},{"note":"For ESM and TypeScript, individual error classes are named exports. The CommonJS default export `Errors` is primarily for `require`.","wrong":"import Errors from 'throwable-http-errors'; const { BadRequest } = Errors;","symbol":"SpecificError (ESM/TypeScript)","correct":"import { BadRequest, InternalServerError } from 'throwable-http-errors';"},{"note":"All specific HTTP error classes extend from `HttpError`. This is useful for `instanceof` checks.","symbol":"BaseHttpError (TypeScript)","correct":"import { HttpError } from 'throwable-http-errors';"}],"quickstart":{"code":"import express from 'express';\nimport { BadRequest, NotFound, InternalServerError } from 'throwable-http-errors';\n\nconst app = express();\napp.use(express.json());\n\ninterface Pet { id: string; name: string; type: string; }\n\n// Dummy database and controller\nconst pets: Pet[] = [{ id: '1', name: 'Buddy', type: 'Dog' }];\nconst PetsController = {\n  create: async (data: any): Promise<Pet> => {\n    if (!data || !data.name || !data.type) {\n      throw new BadRequest('Pet name and type are required.');\n    }\n    const newPet: Pet = { id: String(pets.length + 1), ...data };\n    pets.push(newPet);\n    return newPet;\n  },\n  getById: async (id: string): Promise<Pet> => {\n    const pet = pets.find(p => p.id === id);\n    if (!pet) {\n      throw new NotFound(`Pet with ID ${id} not found.`);\n    }\n    return pet;\n  }\n};\n\napp.post('/pets', async (req, res, next) => {\n  try {\n    const pet = await PetsController.create(req.body);\n    res.status(201).send({ status: true, data: pet });\n  } catch (e) {\n    next(e); // Pass error to the global error handler\n  }\n});\n\napp.get('/pets/:id', async (req, res, next) => {\n  try {\n    const pet = await PetsController.getById(req.params.id);\n    res.status(200).send({ status: true, data: pet });\n  } catch (e) {\n    next(e);\n  }\n});\n\n// Global error handling middleware\napp.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {\n  // All throwable-http-errors instances have a 'status' property\n  if (err.status) {\n    return res.status(err.status).json({ status: false, message: err.message });\n  } else {\n    console.error(err);\n    return res.status(500).json({ status: false, message: 'Internal Server Error' });\n  }\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log('Try: POST /pets with { \"name\": \"Fluffy\", \"type\": \"Cat\" }');\n  console.log('Then: GET /pets/1');\n});","lang":"typescript","description":"Demonstrates creating and handling throwable HTTP errors within an Express.js API using `async/await` and a global error middleware, showcasing `BadRequest` and `NotFound` errors."},"warnings":[{"fix":"Adopt `try/catch` blocks around asynchronous operations and `throw new Errors.SomeError()` instead of `return next(new Errors.SomeError())`.","message":"The library encourages a paradigm shift from passing errors to `next(err)` to explicitly `throw new Errors.SomeError()` within `async` functions. While `next(err)` still works, leveraging `throw` with `try/catch` is the intended modern usage for better code readability and control flow.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Review the library's official changelog (if available) for `throwable-http-errors` v1 to v2. Ensure your error handling middleware correctly identifies and processes `HttpError` instances, potentially using `err instanceof HttpError`.","message":"When migrating from `throwable-http-errors` v1 (if it existed) to v2.x, ensure `instanceof` checks are still valid. Although no explicit breaking changes are documented for v1 to v2 API methods, major version bumps often imply changes in underlying structure or exported symbols. Always test your error handling middleware thoroughly.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Always use the specific named error classes (e.g., `new BadRequest('Invalid input')`) for clarity and consistency, rather than attempting to instantiate a generic error with a status code unless explicitly supported by the `HttpError` base class.","message":"Unlike some other HTTP error libraries (e.g., `http-errors`), `throwable-http-errors` primarily provides pre-defined error classes for standard HTTP status codes (e.g., `BadRequest`, `NotFound`). While it includes a base `HttpError` class, directly creating generic errors by status code (e.g., `new Errors(400, 'message')`) is not the primary pattern.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Always use the `new` keyword when creating an instance of an error class, e.g., `throw new Errors.BadRequest('Invalid data')`.","cause":"Attempting to call an error class directly as a function instead of instantiating it with `new`.","error":"TypeError: Class constructor BadRequest cannot be invoked without 'new'"},{"fix":"Ensure all `async` functions that might throw an error are called with `await` within a `try/catch` block, or that the returned promise has a `.catch()` handler.","cause":"An asynchronous function `throw` an `HttpError` but the calling context did not `await` the promise or failed to catch the rejection.","error":"UnhandledPromiseRejectionWarning: [ErrorName]: [Error Message]"},{"fix":"For CommonJS, use `const Errors = require('throwable-http-errors');`. For ESM/TypeScript, use named imports: `import { BadRequest } from 'throwable-http-errors;`.","cause":"Using `Errors` or specific error classes (e.g., `BadRequest`) without correctly importing them, especially when mixing CommonJS `require` with ESM `import` or vice-versa.","error":"Errors is not defined"},{"fix":"In TypeScript, use a type guard to check if the error is an instance of `HttpError` before accessing `status`: `if (err instanceof HttpError) { console.log(err.status); }`.","cause":"Trying to access the `status` property on a generic `Error` object in TypeScript without first asserting it's an `HttpError` instance.","error":"Property 'status' does not exist on type 'Error'."}],"ecosystem":"npm","meta_description":null}