### Implement AsyncRequestHandler Source: https://github.com/hiprax/errors/blob/main/_autodocs/types.md Example implementation of a request handler using custom Request parameters. ```typescript import { type AsyncRequestHandler } from "@hiprax/errors"; import { Request, Response } from "express"; interface UserParams { id: string; } const getUser: AsyncRequestHandler, Response> = async (req, res) => { const user = await db.users.findById(req.params.id); res.json(user); }; ``` -------------------------------- ### Quick Start with Express Source: https://github.com/hiprax/errors/blob/main/README.md Integrate error handling using catchAsync for route handlers and errorMiddleware for the Express app. ```ts import express from "express"; import { errorMiddleware, catchAsync, httpErrors, } from "@hiprax/errors"; const app = express(); app.get( "/users/:id", catchAsync(async (req, res) => { if (req.params.id === "0") { throw httpErrors.notFound("User not found"); } res.json({ id: req.params.id }); }) ); // Always register last app.use(errorMiddleware); ``` -------------------------------- ### Install @hiprax/errors Source: https://github.com/hiprax/errors/blob/main/README.md Install the package via npm. ```bash npm install @hiprax/errors ``` -------------------------------- ### Setup Basic Express Error Handling Source: https://github.com/hiprax/errors/blob/main/_autodocs/README.md Integrate catchAsync for async route handlers and register errorMiddleware as the final middleware. ```typescript import express from "express"; import { errorMiddleware, catchAsync } from "@hiprax/errors"; const app = express(); app.get( "/users/:id", catchAsync(async (req, res) => { const user = await db.users.findById(req.params.id); res.json(user); }) ); // Always register as the last middleware app.use(errorMiddleware); ``` -------------------------------- ### Configure errorMiddleware with exposeServerErrors Source: https://github.com/hiprax/errors/blob/main/_autodocs/configuration.md Example of initializing the middleware with exposeServerErrors set to false to redact internal server errors in production. ```typescript import { createErrorMiddleware } from "@hiprax/errors"; import express from "express"; const app = express(); // Production-hardened: redact internal errors const middleware = createErrorMiddleware({ exposeServerErrors: false }); app.use(middleware); // Response in production when statusCode >= 500: // { // "success": false, // "message": "Internal Server Error", // Generic, redacted // "statusCode": 500, // "statusText": "Internal Server Error" // } // Response in development (still shows real message): // { // "success": false, // "message": "Database connection failed on line 42", // Real message // "statusCode": 500, // "statusText": "Internal Server Error", // "stack": "Error: Database connection failed..." // } ``` -------------------------------- ### AsyncErrorRequestHandler type binding example Source: https://github.com/hiprax/errors/blob/main/_autodocs/types.md Demonstrates correct usage of type parameters for the error handler. ```typescript // Correct: binds to Req type MyHandler = AsyncErrorRequestHandler; // Wrong: binds to Req, which works at first, but becomes confusing // because Res defaults, then Err defaults, then R defaults ``` -------------------------------- ### Handle system and database errors Source: https://github.com/hiprax/errors/blob/main/_autodocs/errors.md Examples of catching file system and database errors that are mapped to specific HTTP status codes by the middleware. ```typescript // ENOENT example try { await fs.readFile("nonexistent.txt"); } catch (err) { // errorMiddleware handles as 404 "Resource not found" } // Mongo duplicate key try { await User.create({ email: "taken@example.com" }); } catch (err) { // errorMiddleware handles as 400 "Duplicate entry for field(s): email" // err.cause.keyValue contains { email: "taken@example.com" } } ``` -------------------------------- ### Integrate ErrorHandler and AsyncRequestHandler Source: https://github.com/hiprax/errors/blob/main/_autodocs/types.md Examples of typing custom error factories, fetch responses, and route handlers using library types. ```typescript import { ErrorHandler, type ErrorHandlerOptions, type ErrorPayload, type ErrorFactory, type AsyncRequestHandler, } from "@hiprax/errors"; // Type a custom factory const myErrorFactory: ErrorFactory = (message, options) => new ErrorHandler(message, 418, options); // Type a fetch wrapper response async function apiCall(url: string): Promise { const r = await fetch(url); return r.json(); } // Type a route handler const handler: AsyncRequestHandler = async (req, res) => { const data = await apiCall("/api/data"); if (typeof data === "object" && data !== null && "success" in data) { // TypeScript narrows to ErrorPayload if (!data.success) { console.log(`API error: ${data.statusCode} ${data.message}`); } } res.json(data); }; ``` -------------------------------- ### Typed Route Handler Usage Source: https://github.com/hiprax/errors/blob/main/README.md Example of using catchAsync with a typed Express request handler. ```ts import type { Request, Response } from "express"; router.get( "/posts/:id", catchAsync(async (req: Request<{ id: string }>, res: Response) => { const post = await getPost(req.params.id); // ^? string res.json(post); }) ); ``` -------------------------------- ### Throw HTTP Errors Source: https://github.com/hiprax/errors/blob/main/README.md Examples of throwing various HTTP errors with optional custom messages and error causes. ```ts throw httpErrors.notFound(); // "Not found" (404) throw httpErrors.forbidden("Admins only"); // "Admins only" (403) throw httpErrors.conflict("Email taken", { cause: dbErr }); // 409, cause preserved ``` -------------------------------- ### Throwing and Chaining Errors Source: https://github.com/hiprax/errors/blob/main/README.md Examples of throwing an ErrorHandler with a specific status code and wrapping an existing error using the cause option. ```ts import { ErrorHandler } from "@hiprax/errors"; throw new ErrorHandler("Not allowed", 403); // => { message: "Not allowed", statusCode: 403, statusText: "Forbidden" } // Preserve the underlying error for richer logs / chained debugging try { await db.query("SELECT 1"); } catch (err) { throw new ErrorHandler("Lookup failed", 500, { cause: err }); // => err.cause === the original db error } ``` -------------------------------- ### Implement AsyncErrorRequestHandler Source: https://github.com/hiprax/errors/blob/main/_autodocs/types.md Example implementation of an error handler with explicit error type. ```typescript import { type AsyncErrorRequestHandler } from "@hiprax/errors"; import { Request, Response, NextFunction } from "express"; const errorHandler: AsyncErrorRequestHandler = async (err: Error, req: Request, res: Response, next: NextFunction) => { await logError(err); res.status(500).json({ message: "Internal server error" }); }; ``` -------------------------------- ### Express Middleware Arity Normalization Source: https://github.com/hiprax/errors/blob/main/README.md Examples of how catchAsync handles Express middleware arity based on parameter count. ```typescript app.use(catchAsync(myErrorHandler)) ``` ```typescript (err, req, res) ``` -------------------------------- ### Validate Status Code Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorCodes.md Example function to check if a numeric code exists within the errorCodes map. ```typescript import { errorCodes } from "@hiprax/errors"; function isValidHttpStatusCode(code: number): boolean { return errorCodes.has(code); } isValidHttpStatusCode(200); // false (2xx not in the map) isValidHttpStatusCode(404); // true isValidHttpStatusCode(999); // false ``` -------------------------------- ### Library Entry Point Exports Source: https://github.com/hiprax/errors/blob/main/_autodocs/README.md Import the core classes, middleware, functions, and types from the @hiprax/errors package. ```typescript import { // Classes ErrorHandler, // Middleware and functions errorMiddleware, createErrorMiddleware, handleCommonErrors, catchAsync, httpErrors, errorCodes, // Types type ErrorHandlerOptions, type ErrorPayload, type ErrorMiddlewareOptions, type ErrorFactory, type AsyncRequestHandler, type AsyncErrorRequestHandler, type WrappedResult, } from "@hiprax/errors"; ``` -------------------------------- ### Project Documentation Directory Structure Source: https://github.com/hiprax/errors/blob/main/_autodocs/MANIFEST.md Visual representation of the documentation file hierarchy. ```text output/ ├── README.md (Main entry point) ├── INDEX.md (Directory guide) ├── MANIFEST.md (This file) ├── types.md (Type definitions) ├── errors.md (Error mapping reference) ├── configuration.md (Configuration guide) └── api-reference/ ├── ErrorHandler.md (Error class) ├── errorMiddleware.md (Middleware) ├── handleCommonErrors.md (Error mapper) ├── catchAsync.md (Async wrapper) ├── httpErrors.md (HTTP error factories) └── errorCodes.md (Status code reference) ``` -------------------------------- ### Demonstrate Payload Constraints Source: https://github.com/hiprax/errors/blob/main/_autodocs/configuration.md Illustrates how the middleware handles stack trace truncation and non-serializable values in error responses. ```typescript // Stack trace truncation const bigStack = new Error("test"); bigStack.stack = "x".repeat(15000); // Response in development (truncated): // { // "stack": "xxxx... [stack truncated]" // } // Non-serializable value handling const payload = { success: false, message: "error", fn: () => {} // Functions are non-serializable }; // Middleware sanitizes and retries, replacing function with undefined ``` -------------------------------- ### Function and Class Decorator Usage Source: https://github.com/hiprax/errors/blob/main/README.md Demonstrates applying catchAsync as a function wrapper and as a class decorator. ```ts // Function wrapper router.get( "/posts", catchAsync(async (req, res) => { const posts = await listPosts(); res.json(posts); }) ); // Class decorator (works with both legacy and stage-3 decorators) @catchAsync class UserController { async getUser(req: Request, res: Response) { res.json({ id: req.params.id }); } } // Manual application is also supported and behaves identically class OrderController { async list(req: Request, res: Response) { res.json(await loadOrders()); } } const WrappedOrderController = catchAsync(OrderController); ``` -------------------------------- ### Run project tests Source: https://github.com/hiprax/errors/blob/main/README.md Execute the Jest test suite or run compile-time type assertions. ```bash npm test # Jest suite covering all modules npm run test:types # compile-time assertions over the type signatures in src/ ``` -------------------------------- ### Using Default Messages Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/httpErrors.md Demonstrates throwing standard HTTP errors using the default messages provided by the factory. ```typescript import { httpErrors } from "@hiprax/errors"; throw httpErrors.notFound(); // => ErrorHandler { // message: "Not found", // statusCode: 404, // statusText: "Not Found" // } throw httpErrors.unauthorized(); // => ErrorHandler { // message: "Unauthorized", // statusCode: 401, // statusText: "Unauthorized" // } ``` -------------------------------- ### catchAsync(constructor) Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/catchAsync.md Wraps all prototype methods of an Express controller class using decorator syntax. ```APIDOC ## catchAsync(constructor) ### Description Acts as a class decorator to wrap all prototype methods of an Express controller class, ensuring errors in any method are caught and forwarded. ### Parameters - **constructor** (Class) - Required - The controller class constructor to be decorated. - **context** (ClassDecoratorContext) - Optional - Stage-3 decorator context (ignored at runtime). ### Returns - **Class** - The decorated constructor with all methods wrapped. ``` -------------------------------- ### Typed Request Parameters with catchAsync Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/catchAsync.md Demonstrates usage of catchAsync with TypeScript interfaces for request parameters. ```typescript import { Router, Request, Response } from "express"; import { catchAsync } from "@hiprax/errors"; interface PostParams { id: string; } const router = Router(); router.get( "/posts/:id", catchAsync(async (req: Request, res: Response) => { const postId = req.params.id; // Correctly typed as string const post = await db.posts.findById(postId); res.json(post); }) ); ``` -------------------------------- ### createErrorMiddleware Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorMiddleware.md Factory function to build a configured error middleware instance. ```APIDOC ## createErrorMiddleware ### Description Builds a configured error middleware with optional response hardening, such as redacting server-error messages in production environments. ### Parameters - **options** (ErrorMiddlewareOptions) - Optional - Configuration options. - **exposeServerErrors** (boolean) - Optional - Default: true. When false, redacts 5xx messages to generic status text in production. ### Returns - **ErrorRequestHandler** - An error handler configured with the provided options. ``` -------------------------------- ### Configuring Response Hardening Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorMiddleware.md Use createErrorMiddleware to control error exposure, such as redacting internal server error details in production environments. ```typescript import express from "express"; import { createErrorMiddleware } from "@hiprax/errors"; const app = express(); // In production, redact internal error details to generic status text // In development/test, show full messages for debugging app.use( createErrorMiddleware({ exposeServerErrors: false // Redact 5xx in production }) ); app.listen(3000); ``` -------------------------------- ### Importing and Using Hiprax Error Types Source: https://github.com/hiprax/errors/blob/main/README.md Demonstrates importing core error types and implementing a custom error factory and fetch response typing. ```ts import { ErrorHandler, type ErrorHandlerOptions, type ErrorPayload, type ErrorFactory, } from "@hiprax/errors"; // Build your own factory with the same signature shape const teapot: ErrorFactory = (message = "I'm a teapot", options) => new ErrorHandler(message, 418, options); // Type a fetch wrapper response async function call(url: string): Promise { const r = await fetch(url); return r.json(); } ``` -------------------------------- ### Configure legacy decorators in tsconfig.json Source: https://github.com/hiprax/errors/blob/main/_autodocs/configuration.md Enable experimental decorators for TypeScript projects that do not use the Stage-3 decorator standard. ```jsonc // tsconfig.json for legacy decorators { "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": false } } ``` -------------------------------- ### createErrorMiddleware Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorMiddleware.md Factory function to create a configured error middleware instance. ```APIDOC ## createErrorMiddleware(options) ### Description Creates a customized error middleware instance with specific configuration options. ### Parameters - **options** (object) - Configuration object. - **exposeServerErrors** (boolean) - Optional. If false, redacts internal 5xx error details in production environments. ``` -------------------------------- ### Implement ErrorHandler with options Source: https://github.com/hiprax/errors/blob/main/_autodocs/types.md Demonstrates passing an original error to the ErrorHandler constructor using ErrorHandlerOptions. ```typescript import { ErrorHandler, type ErrorHandlerOptions } from "@hiprax/errors"; function createError(message: string, original: Error): ErrorHandler { const options: ErrorHandlerOptions = { cause: original }; return new ErrorHandler(message, 500, options); } ``` -------------------------------- ### Basic ErrorHandler Usage Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/ErrorHandler.md Demonstrates throwing errors with default or custom messages and status codes. ```typescript import { ErrorHandler } from "@hiprax/errors"; // Simple error with default message throw new ErrorHandler(undefined, 404); // => { message: "Something went wrong! Please try again", statusCode: 404, statusText: "Not Found" } // Custom message with explicit status code throw new ErrorHandler("User account locked", 403); // => { message: "User account locked", statusCode: 403, statusText: "Forbidden" } ``` -------------------------------- ### Initialize ErrorHandler constructor Source: https://github.com/hiprax/errors/blob/main/_autodocs/configuration.md Defines the signature for creating a new ErrorHandler instance. ```typescript new ErrorHandler( message?: string, statusCode?: number, options?: ErrorHandlerOptions ) ``` -------------------------------- ### Configure errorMiddleware environment behavior Source: https://github.com/hiprax/errors/blob/main/_autodocs/configuration.md Demonstrates how NODE_ENV affects error response output when using createErrorMiddleware. ```typescript // Development // NODE_ENV=development const middleware = createErrorMiddleware({ exposeServerErrors: false }); // Stack trace still included (development gate takes precedence) // Server error message still exposed // Production // NODE_ENV=production const middleware = createErrorMiddleware({ exposeServerErrors: false }); // No stack trace in response // Server error message replaced with generic text (e.g., "Internal Server Error") ``` -------------------------------- ### Unit Testing Wrapped Methods Source: https://github.com/hiprax/errors/blob/main/README.md Shows how to invoke a wrapped controller method in unit tests by providing a mock next function. ```typescript controller.method(req, res) ``` ```typescript jest.fn() ``` -------------------------------- ### Configure createErrorMiddleware Source: https://github.com/hiprax/errors/blob/main/README.md Use the factory function to customize middleware behavior, such as redacting server error messages in production environments. ```ts import { createErrorMiddleware } from "@hiprax/errors"; // Redact 5xx messages to the generic status text in production app.use(createErrorMiddleware({ exposeServerErrors: false })); ``` -------------------------------- ### Instantiate ErrorHandler with cause Source: https://github.com/hiprax/errors/blob/main/_autodocs/configuration.md Shows how to pass an original error to the cause option for structured logging. ```typescript import { ErrorHandler } from "@hiprax/errors"; new ErrorHandler("Failed to fetch user", 500, { cause: originalDatabaseError }); // error.cause → originalDatabaseError (accessible to structured loggers) ``` -------------------------------- ### Import errorCodes Source: https://github.com/hiprax/errors/blob/main/README.md Import the read-only map of HTTP status codes. ```ts import { errorCodes } from "@hiprax/errors"; ``` -------------------------------- ### ErrorMiddlewareOptions Source: https://github.com/hiprax/errors/blob/main/_autodocs/types.md Configuration options for the createErrorMiddleware function, allowing control over server error exposure. ```APIDOC ## ErrorMiddlewareOptions ### Description Configuration options for `createErrorMiddleware`. Enables opt-in response hardening, such as redacting server-error messages in production to prevent information disclosure. ### Properties - **exposeServerErrors** (boolean) - Optional - When `false`, redact 5xx messages to generic status text in production (`NODE_ENV === "production"`). Defaults to `true`. ``` -------------------------------- ### Apply Class Decorator (Legacy) Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/catchAsync.md Wraps all prototype methods of a controller class using legacy decorator syntax. ```typescript catchAsync any>( constructor: T ): T ``` -------------------------------- ### Configuring Production Error Redaction Source: https://github.com/hiprax/errors/blob/main/_autodocs/errors.md Configure createErrorMiddleware with exposeServerErrors set to false to prevent leaking internal error details in production environments. ```typescript import { createErrorMiddleware } from "@hiprax/errors"; const middleware = createErrorMiddleware({ exposeServerErrors: false }); // In production, any statusCode >= 500 gets its message replaced with the generic status text // E.g., "Internal error at line 42" → "Internal Server Error" // Original error stays on .cause for logging ``` -------------------------------- ### Implement Conditional Error Factories Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/httpErrors.md Demonstrates throwing specific HTTP errors based on application logic conditions such as missing resources, insufficient permissions, or rate limiting. ```typescript import { httpErrors } from "@hiprax/errors"; function getResource(id: string, resource: object | null) { if (!resource) { throw httpErrors.notFound(`Resource ${id} not found`); } return resource; } function enforceAdmin(user: { role: string }) { if (user.role !== "admin") { throw httpErrors.forbidden("This action requires admin privileges"); } } function checkRateLimit(requestCount: number, limit: number) { if (requestCount > limit) { throw httpErrors.tooManyRequests("Rate limit exceeded"); } } ``` -------------------------------- ### Import httpErrors Source: https://github.com/hiprax/errors/blob/main/README.md Import the httpErrors factory object from the library. ```ts import { httpErrors } from "@hiprax/errors"; ``` -------------------------------- ### Handling Fallback and Unknown Error Types Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/handleCommonErrors.md Demonstrates how the utility handles custom error properties, non-error values, and errors missing messages. ```typescript import { handleCommonErrors } from "@hiprax/errors"; // Unknown error type const customErr = new Error("Custom error"); customErr.statusCode = 418; // Custom property handleCommonErrors(customErr); // statusCode: 418 (from err.statusCode) // message: "Custom error" // Non-Error value handleCommonErrors("string error"); // statusCode: 500 // message: "Unexpected error occurred" // Error without message const noMsg = new Error(); noMsg.name = "SomethingElse"; handleCommonErrors(noMsg); // statusCode: 500 // message: "Unhandled server error" ``` -------------------------------- ### Method Arity and Type Safety Source: https://github.com/hiprax/errors/blob/main/README.md Illustrates the discrepancy between runtime requirements and compile-time type signatures for decorated methods. ```typescript async getUser(req, res) ``` ```typescript controller.getUser(req, res, next) ``` ```typescript controller.getUser(req, res) ``` -------------------------------- ### Apply catchAsync via Manual Class Wrapping Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/catchAsync.md Wraps a class manually at the definition site to ensure all methods forward errors to middleware. ```typescript import { catchAsync } from "@hiprax/errors"; class ProductController { async list(req, res) { res.json(await db.products.find()); } } // Manually apply decorator at definition site const WrappedController = catchAsync(ProductController); const controller = new WrappedController(); router.get("/products", controller.list); ``` -------------------------------- ### Manual Wrapping and Idempotency Source: https://github.com/hiprax/errors/blob/main/README.md Demonstrates manual wrapping of a class or function, noting that the operation is idempotent. ```typescript const Wrapped = catchAsync(MyClass) ``` ```typescript catchAsync(catchAsync(fn)) === catchAsync(fn) ``` -------------------------------- ### Apply Class Decorator (Stage-3) Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/catchAsync.md Wraps a controller class using the stage-3 ECMAScript decorator protocol. ```typescript catchAsync any>( value: T, context: ClassDecoratorContext ): T ``` -------------------------------- ### Configure Production Error Middleware Source: https://github.com/hiprax/errors/blob/main/_autodocs/README.md Use createErrorMiddleware to redact internal error details when running in production environments. ```typescript import { createErrorMiddleware } from "@hiprax/errors"; // Redact internal error details in production app.use( createErrorMiddleware({ exposeServerErrors: false }) ); ``` -------------------------------- ### Customize httpErrors factories Source: https://github.com/hiprax/errors/blob/main/_autodocs/configuration.md Demonstrates overriding default messages in predefined factories and creating custom error factories using ErrorHandler. ```typescript import { httpErrors, ErrorHandler, type ErrorFactory } from "@hiprax/errors"; // Use predefined factory with override throw httpErrors.notFound("Custom user not found message"); // Create custom factory with different status code const customError: ErrorFactory = (message = "Custom error", options) => new ErrorHandler(message, 418, options); throw customError("I'm a teapot"); ``` -------------------------------- ### ErrorHandlerOptions Source: https://github.com/hiprax/errors/blob/main/_autodocs/types.md Configuration interface for the ErrorHandler constructor, allowing the attachment of an underlying cause for structured logging. ```APIDOC ## ErrorHandlerOptions ### Description Options bag for the ErrorHandler constructor. Mirrors the ES2022 ErrorOptions shape so callers can attach an underlying error for structured logging. ### Properties - **cause** (unknown) - Optional - The original error that caused this one; forwarded to the native Error constructor ``` -------------------------------- ### catchAsync(fn) Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/catchAsync.md Wraps an Express request handler (0-3 parameters) or error handler (4+ parameters) to automatically catch and forward errors to the next() function. ```APIDOC ## catchAsync(fn) ### Description Wraps an async or sync request handler or error handler. It catches errors and rejected promises, forwarding them to the Express error handler via next(). ### Parameters - **fn** (Function) - Required - The handler function to wrap. If it declares 4 parameters, it is treated as an error handler. ### Returns - **Function** - A wrapped handler that matches the expected Express signature (3 parameters for request handlers, 4 for error handlers). ``` -------------------------------- ### Basic Request Handler with catchAsync Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/catchAsync.md Wraps an asynchronous route handler to ensure thrown errors are forwarded to Express error middleware. ```typescript import { Router } from "express"; import { catchAsync } from "@hiprax/errors"; const router = Router(); router.get( "/posts/:id", catchAsync(async (req, res) => { const post = await db.posts.findById(req.params.id); if (!post) { throw new Error("Post not found"); } res.json(post); }) ); // Without catchAsync, a thrown error would crash the server or hang. // With catchAsync, the error is forwarded to error middleware via next(). ``` -------------------------------- ### new ErrorHandler(message, statusCode, options) Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/ErrorHandler.md Constructs a new ErrorHandler instance to be thrown within an application, allowing for custom messages, HTTP status codes, and error cause preservation. ```APIDOC ## constructor(message, statusCode, options) ### Description Creates a new instance of ErrorHandler. This class is designed to be thrown, allowing Express error middleware to catch and process the error with appropriate HTTP status codes. ### Parameters - **message** (string) - Optional - Human-readable error message. Defaults to "Something went wrong! Please try again". - **statusCode** (number) - Optional - HTTP status code. Defaults to 500. Unknown codes are normalized to 500. - **options** (ErrorHandlerOptions) - Optional - ES2022 error options bag; pass { cause: originalError } to preserve the underlying error. ### Properties - **name** (string) - Always "ErrorHandler". - **message** (string) - The error message. - **statusCode** (number) - The HTTP status code. - **statusText** (string | undefined) - Human-readable HTTP status text. - **cause** (unknown) - The original error if provided. - **stack** (string) - The captured stack trace. ### Example ```typescript import { ErrorHandler } from "@hiprax/errors"; // Throwing a 404 error throw new ErrorHandler("Resource not found", 404); // Throwing with a cause try { // ... } catch (err) { throw new ErrorHandler("Operation failed", 500, { cause: err }); } ``` ``` -------------------------------- ### Create Custom Error Factory with Validation Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorCodes.md Demonstrates wrapping the ErrorHandler to validate status codes against the errorCodes map, falling back to 500 for unknown codes. ```typescript import { errorCodes } from "@hiprax/errors"; import ErrorHandler from "./ErrorHandler"; function createCustomError( message: string, statusCode: number ): ErrorHandler { if (!errorCodes.has(statusCode)) { // Fallback to 500 for unknown codes (same behavior as ErrorHandler) return new ErrorHandler(message, 500); } return new ErrorHandler(message, statusCode); } createCustomError("Not found", 404); // 404 createCustomError("Bad code", 999); // 500 (normalized) ``` -------------------------------- ### Handle SyntaxError Source: https://github.com/hiprax/errors/blob/main/_autodocs/errors.md Shows how JSON parsing or syntax errors are caught and mapped to a 400 status. ```typescript try { JSON.parse("{ invalid json }"); } catch (err) { // Handled as 400 "Malformed JSON or invalid syntax" } ``` -------------------------------- ### Log All Error Codes Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorCodes.md Iterates through the errorCodes map to categorize and log client and server errors. ```typescript import { errorCodes } from "@hiprax/errors"; console.log("Supported HTTP error codes:"); for (const [code, text] of errorCodes) { if (code >= 400 && code < 500) { console.log(` ${code} ${text} (client error)`); } else if (code >= 500) { console.log(` ${code} ${text} (server error)`); } } ``` -------------------------------- ### handleCommonErrors(err: unknown) Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/handleCommonErrors.md Standardizes various library-specific errors into a consistent format with appropriate status codes and messages, while preserving the original error in the cause property. ```APIDOC ## handleCommonErrors(err) ### Description Standardizes errors thrown by external libraries (Mongoose, JWT, Axios) into a consistent structure. It maps specific library error types to appropriate HTTP status codes and user-friendly messages while maintaining the original error in the `cause` property for diagnostic purposes. ### Signature `handleCommonErrors(err: unknown): StandardizedError` ### Parameters - **err** (unknown) - Required - The caught error object from a try/catch block. ### Returns - **statusCode** (number) - The mapped HTTP status code. - **message** (string) - A human-readable error message. - **cause** (Error) - The original error object, preserving the stack trace and library-specific metadata. ### Usage Example ```typescript import { handleCommonErrors } from "@hiprax/errors"; try { // Perform operation } catch (err) { const standardized = handleCommonErrors(err); console.log(standardized.statusCode); console.log(standardized.message); } ``` ``` -------------------------------- ### catchAsync Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorMiddleware.md Utility wrapper to catch asynchronous errors in route handlers. ```APIDOC ## catchAsync(fn) ### Description Wraps an asynchronous route handler to automatically pass errors to the next middleware. ``` -------------------------------- ### ErrorHandler Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorMiddleware.md Class for creating custom errors with specific status codes and causes. ```APIDOC ## new ErrorHandler(message, statusCode, options) ### Parameters - **message** (string) - The error message. - **statusCode** (number) - The HTTP status code to return. - **options** (object) - Optional. - **cause** (Error) - The underlying error that caused this exception. ``` -------------------------------- ### Handle JWT Authentication Errors Source: https://github.com/hiprax/errors/blob/main/_autodocs/errors.md Illustrates how various JWT-related errors are unified into a single 401 response. ```typescript try { const token = getTokenFromHeader(); jwt.verify(token, SECRET); } catch (err) { // All three types → 401 with unified message // err.cause contains the original JWT error for structured logging } ``` -------------------------------- ### Error Wrapping Behavior Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/catchAsync.md Demonstrates how non-Error thrown values are converted into Error instances. ```typescript throw "string"; // → Error("Non-Error thrown/rejected: string") throw null; // → Error("Non-Error thrown/rejected: null") throw { code: 42 }; // → Error("Non-Error thrown/rejected: [object Object]") ``` -------------------------------- ### Handle custom errors with default mapping Source: https://github.com/hiprax/errors/blob/main/_autodocs/errors.md Demonstrates how handleCommonErrors processes custom error classes by preserving status codes and messages. ```typescript class CustomError extends Error { constructor(message: string, public statusCode: number) { super(message); this.name = "CustomError"; } } try { throw new CustomError("Custom app error", 418); } catch (err) { const handled = handleCommonErrors(err); // statusCode: 418 // message: "Custom app error" // cause: the original CustomError } ``` -------------------------------- ### Build Status Message Map Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorCodes.md Converts the frozen errorCodes map into a standard JavaScript object. ```typescript import { errorCodes } from "@hiprax/errors"; // Create a mapping object from the frozen map const statusTextMap: Record = {}; for (const [code, text] of errorCodes) { statusTextMap[code] = text; } statusTextMap[404]; // "Not Found" ``` -------------------------------- ### Implement Structured Error Logging Source: https://github.com/hiprax/errors/blob/main/_autodocs/README.md Normalize errors using handleCommonErrors to ensure consistent logging and access to the error cause chain. ```typescript import { handleCommonErrors } from "@hiprax/errors"; import logger from "pino-logger"; try { await riskyOperation(); } catch (err) { const handled = handleCommonErrors(err); // Log with full cause chain for debugging logger.error(handled); // handled.cause contains original library-specific error } ``` -------------------------------- ### Apply catchAsync as a Legacy Class Decorator Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/catchAsync.md Requires experimentalDecorators enabled in tsconfig.json to wrap class methods for error forwarding. ```typescript // tsconfig.json { "compilerOptions": { "experimentalDecorators": true } } // controller.ts import { catchAsync } from "@hiprax/errors"; @catchAsync class OrderController { async listOrders(req, res) { const orders = await db.orders.find(); res.json(orders); } async getOrder(req, res) { const order = await db.orders.findById(req.params.id); res.json(order); } } // Both methods are now wrapped and will forward errors to middleware ``` -------------------------------- ### Use ErrorHandler in TypeScript Source: https://github.com/hiprax/errors/blob/main/_autodocs/types.md Demonstrates using ErrorHandler as a type for function parameters and as a value for throwing errors. ```typescript import { ErrorHandler } from "@hiprax/errors"; // As a type function handleError(err: ErrorHandler): void { console.log(err.statusCode); } // As a value (instantiation) throw new ErrorHandler("Custom message", 500); ``` -------------------------------- ### ErrorHandler Constructor Source: https://github.com/hiprax/errors/blob/main/README.md Creates a new instance of ErrorHandler, a custom Error subclass that includes HTTP status information. ```APIDOC ## ErrorHandler Constructor ### Description Creates a new ErrorHandler instance with a message, status code, and optional error cause. ### Signature `new ErrorHandler(message?: string, statusCode?: number, options?: { cause?: unknown })` ### Parameters - **message** (string) - Optional - Error message. Defaults to "Something went wrong! Please try again". - **statusCode** (number) - Optional - HTTP status code. Defaults to 500. - **options** (object) - Optional - ES2022 options bag. Use `{ cause: originalError }` to preserve the underlying error. ### Properties - **statusCode** (number) - The HTTP status code associated with the error. - **statusText** (string) - The HTTP status text resolved from the status code. ### Usage Example ```ts import { ErrorHandler } from "@hiprax/errors"; // Basic usage throw new ErrorHandler("Not allowed", 403); // With error chaining try { await db.query("SELECT 1"); } catch (err) { throw new ErrorHandler("Lookup failed", 500, { cause: err }); } ``` ``` -------------------------------- ### Wrap Controller Classes with catchAsync Source: https://github.com/hiprax/errors/blob/main/_autodocs/README.md Apply the catchAsync decorator to controller classes to automatically handle errors in all class methods. ```typescript import { catchAsync } from "@hiprax/errors"; @catchAsync class UserController { async getUser(req, res) { res.json(await db.users.findById(req.params.id)); } async createUser(req, res) { const user = await db.users.create(req.body); res.status(201).json(user); } } ``` -------------------------------- ### Class Decorator Type Signature Mismatch Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/catchAsync.md Demonstrates how class decorators fail to update method signatures at the type level, leading to runtime errors when calling methods manually. ```typescript @catchAsync class MyController { async getUser(req, res) { // Declares 2 params // ... } } const c = new MyController(); c.getUser(req, res); // Compile: OK; Runtime: never runs c.getUser(req, res, next); // Compile: ERROR; Runtime: works ``` -------------------------------- ### Consume ErrorPayload in fetch Source: https://github.com/hiprax/errors/blob/main/_autodocs/types.md Shows how to use ErrorPayload to narrow types when handling API responses. ```typescript import { type ErrorPayload } from "@hiprax/errors"; async function fetchData(url: string): Promise { const response = await fetch(url); return response.json(); } const result = await fetchData("/api/users"); if (result.success === false) { // TypeScript narrows to ErrorPayload console.log(`Error ${result.statusCode}: ${result.message}`); } ``` -------------------------------- ### catchAsync Type Definitions Source: https://github.com/hiprax/errors/blob/main/README.md Type signatures for the catchAsync utility, covering request handlers, error handlers, and class decorators. ```ts // The constraints are deliberately the loosest parameterizations, so any // `Request` and any interface extending `Request` is accepted. type ReqLike = Request; type ResLike = Response; // request handler: 0-3 declared parameters in, always 3 out catchAsync( fn: (req: Req, res: Res, next: NextFunction) => R ): (req: Req, res: Res, next: NextFunction) => WrappedResult; // error handler: declare all 4 parameters. Note `Err` comes AFTER `Req`/`Res`, // so a single explicit type argument binds to `Req` and is rejected cleanly // rather than silently mistyping the remaining parameters. catchAsync( fn: (err: Err, req: Req, res: Res, next: NextFunction) => R ): (err: Err, req: Req, res: Res, next: NextFunction) => WrappedResult; // class decorator, and the manual `catchAsync(MyClass)` call site catchAsync any>(constructor: T): T; catchAsync any>(value: T, context: ClassDecoratorContext): T; ``` -------------------------------- ### Preserving Error Cause Chains in TypeScript Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/httpErrors.md Demonstrates wrapping original errors with a cause to maintain stack traces and context for structured logging. ```typescript import { httpErrors } from "@hiprax/errors"; try { const user = await db.users.findById(id); if (!user) { throw httpErrors.notFound("User not found"); } } catch (err) { // Forward with cause for structured logging throw httpErrors.internalServerError("Failed to retrieve user", { cause: err }); } // Accessible to loggers: // error.cause → the original database error with query details ``` -------------------------------- ### Capture errors with Sentry Source: https://github.com/hiprax/errors/blob/main/_autodocs/errors.md Integrates error handling within an Express-style middleware to capture exceptions and return JSON responses. ```typescript import * as Sentry from "@sentry/node"; app.use((err, req, res, next) => { const handled = handleCommonErrors(err); // Sentry walks err.cause to capture full context Sentry.captureException(handled); res.status(handled.statusCode).json({ message: handled.message, statusCode: handled.statusCode }); }); ``` -------------------------------- ### ErrorHandler Constructor Signature Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/ErrorHandler.md The constructor accepts an optional message, status code, and error options. ```typescript constructor( message?: string, statusCode?: number, options?: ErrorHandlerOptions ) ``` -------------------------------- ### Handling Common Errors and Async Routes Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorMiddleware.md Utilize catchAsync to wrap route handlers and automatically map common errors like Mongoose validation or JWT issues to appropriate status codes. ```typescript import express, { Router } from "express"; import { errorMiddleware, catchAsync, ErrorHandler } from "@hiprax/errors"; const app = express(); const router = Router(); // Mongoose validation error (automatic mapping via handleCommonErrors) router.post( "/users", catchAsync(async (req, res) => { const user = new User(req.body); await user.save(); // ValidationError thrown by Mongoose res.json(user); }) ); // JWT error (automatic mapping) router.get( "/protected", catchAsync((req, res) => { const token = req.headers.authorization?.split(" ")[1]; const decoded = verifyJWT(token); // May throw JsonWebTokenError res.json({ decoded }); }) ); // Manual error with cause chain router.get( "/data", catchAsync(async (req, res) => { try { const result = await externalAPI.get("/data"); res.json(result); } catch (err) { throw new ErrorHandler("Failed to fetch data", 502, { cause: err }); } }) ); app.use(router); app.use(errorMiddleware); app.listen(3000); // Response for any unhandled error: // { // "success": false, // "message": "...", // "statusCode": 500, // "statusText": "Internal Server Error", // "stack": "..." (dev only) // } ``` -------------------------------- ### Custom Message Overrides Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/httpErrors.md Demonstrates providing a custom string to override the default error message during instantiation. ```typescript import { httpErrors } from "@hiprax/errors"; throw httpErrors.notFound("User account not found"); // => ErrorHandler { // message: "User account not found", // statusCode: 404, // statusText: "Not Found" // } throw httpErrors.conflict("Email address already in use"); // => ErrorHandler { // message: "Email address already in use", // statusCode: 409, // statusText: "Conflict" // } throw httpErrors.forbidden("Admin access required"); // => ErrorHandler { // message: "Admin access required", // statusCode: 403, // statusText: "Forbidden" // } ``` -------------------------------- ### Registering Basic Error Middleware Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorMiddleware.md Register the error middleware as the final step in the Express middleware chain to catch unhandled exceptions. ```typescript import express from "express"; import { errorMiddleware } from "@hiprax/errors"; const app = express(); // ... define your routes ... // Always register as the last middleware app.use(errorMiddleware); app.listen(3000); ``` -------------------------------- ### Manual Invocation Requirements Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/catchAsync.md Shows that wrapped handlers require the Express next callback as the final argument to execute correctly. ```typescript const handler = catchAsync(async (req, res) => { /* ... */ }); handler(req, res, next); // Works handler(req, res); // Returns undefined, never invokes body ``` -------------------------------- ### Log errors with Pino Source: https://github.com/hiprax/errors/blob/main/_autodocs/errors.md Utilizes Pino's built-in error serializer to automatically walk the error cause chain. ```typescript import pino from "pino"; const logger = pino({ // Pino's built-in error serializer walks err.cause automatically }); try { await someAsyncOperation(); } catch (err) { const handled = handleCommonErrors(err); logger.error(handled); // Full cause chain logged } ``` -------------------------------- ### createErrorMiddleware Factory Signature Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorMiddleware.md Factory function to generate configured error middleware, supporting response hardening options. ```typescript createErrorMiddleware( options?: ErrorMiddlewareOptions ): ErrorRequestHandler ``` -------------------------------- ### Define Custom Error Factories Source: https://github.com/hiprax/errors/blob/main/_autodocs/README.md Create specialized error factories using the ErrorHandler class to standardize custom HTTP error responses. ```typescript import { ErrorHandler, type ErrorFactory } from "@hiprax/errors"; const teapot: ErrorFactory = (message = "I'm a teapot", options) => new ErrorHandler(message, 418, options); throw teapot(); ``` -------------------------------- ### Use WrappedResult with catchAsync Source: https://github.com/hiprax/errors/blob/main/_autodocs/types.md Demonstrates how the WrappedResult type signature is applied to a wrapped Express handler. ```typescript import { catchAsync, type WrappedResult } from "@hiprax/errors"; import { Request, Response, NextFunction } from "express"; // Define the original handler const handler = async (req: Request, res: Response, next: NextFunction) => { return { success: true }; }; // Wrapped handler has this signature: const wrapped = catchAsync(handler); // (req: Request, res: Response, next: NextFunction) // => WrappedResult<{ success: true }> // => Promise<{ success: true } | undefined> ``` -------------------------------- ### Define ErrorMiddlewareOptions Interface Source: https://github.com/hiprax/errors/blob/main/_autodocs/types.md Defines the configuration structure for error middleware, allowing control over server error exposure. ```typescript interface ErrorMiddlewareOptions { exposeServerErrors?: boolean; } ``` -------------------------------- ### Configure Application-Level Error Middleware Source: https://github.com/hiprax/errors/blob/main/_autodocs/configuration.md Integrates error middleware into an Express application, using different configurations for production and development environments. ```typescript import express from "express"; import { errorMiddleware, createErrorMiddleware, catchAsync, } from "@hiprax/errors"; const app = express(); app.use(express.json()); // Routes app.get( "/api/users/:id", catchAsync(async (req, res) => { const user = await db.users.findById(req.params.id); res.json(user); }) ); // Error middleware (always last) if (process.env.NODE_ENV === "production") { // Production: redact internal error details app.use( createErrorMiddleware({ exposeServerErrors: false }) ); } else { // Development: full error details for debugging app.use(errorMiddleware); } app.listen(3000); ``` -------------------------------- ### Read Operations for errorCodes Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorCodes.md Demonstrates standard Map read methods and iteration patterns for the errorCodes object. ```typescript errorCodes.get(404) // "Not Found" errorCodes.has(418) // true errorCodes.has(999) // false errorCodes.size // 33 (total codes defined) // Iteration for (const [code, text] of errorCodes) { console.log(`${code}: ${text}`); } for (const code of errorCodes.keys()) { // Iterate over codes } for (const text of errorCodes.values()) { // Iterate over text descriptions } for (const [code, text] of errorCodes.entries()) { // Iterate over both } errorCodes.forEach((text, code) => { // ForEach iteration }); ``` -------------------------------- ### Handle Zod validation errors Source: https://github.com/hiprax/errors/blob/main/_autodocs/errors.md Demonstrates catching a Zod validation failure which results in a 400 HTTP status. ```typescript try { const schema = z.object({ email: z.string().email(), age: z.number().min(18) }); schema.parse({ email: "invalid", age: 10 }); } catch (err) { // Handled as 400 with joined validation messages } ``` -------------------------------- ### Internal ErrorHandler Logic Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorCodes.md Shows how the ErrorHandler constructor utilizes the errorCodes map for status code normalization and text resolution. ```typescript // Inside ErrorHandler constructor: this.statusCode = errorCodes.has(statusCode) ? statusCode : 500; this.statusText = errorCodes.get(this.statusCode); ``` -------------------------------- ### Configure production error exposure Source: https://github.com/hiprax/errors/blob/main/_autodocs/configuration.md Set exposeServerErrors to false to prevent leaking internal error details to clients in production environments. ```typescript createErrorMiddleware({ exposeServerErrors: false }) ``` -------------------------------- ### Apply catchAsync as a Stage-3 Class Decorator Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/catchAsync.md Wraps all methods within a class to handle asynchronous errors automatically using Stage-3 decorator syntax. ```typescript import { Request, Response, Router } from "express"; import { catchAsync } from "@hiprax/errors"; @catchAsync class UserController { async getUser(req: Request, res: Response) { const user = await db.users.findById(req.params.id); if (!user) throw new Error("User not found"); res.json(user); } async createUser(req: Request, res: Response) { const user = await db.users.create(req.body); res.status(201).json(user); } } const controller = new UserController(); const router = Router(); router.get("/users/:id", controller.getUser); router.post("/users", controller.createUser); ``` -------------------------------- ### errorMiddleware Function Signature Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorMiddleware.md Standard Express error-handling middleware signature requiring four parameters. ```typescript errorMiddleware: ( err: any, req: Request, res: Response, next: NextFunction ) => void ``` -------------------------------- ### Record exceptions with OpenTelemetry Source: https://github.com/hiprax/errors/blob/main/_autodocs/errors.md Records an exception on an active span, ensuring the full cause chain is preserved for tracing. ```typescript import { context, trace } from "@opentelemetry/api"; const span = trace.getActiveSpan(); try { await riskyOperation(); } catch (err) { const handled = handleCommonErrors(err); // Record exception with full cause chain span?.recordException(handled, { "exception.escaped": false }); } ``` -------------------------------- ### errorMiddleware Source: https://github.com/hiprax/errors/blob/main/_autodocs/api-reference/errorMiddleware.md The standard error handling middleware to be registered as the final middleware in an Express application. ```APIDOC ## errorMiddleware ### Description Registers the standard error handler to catch and format errors thrown within Express routes. ### Usage `app.use(errorMiddleware);` ### Response Format - **success** (boolean) - Indicates the request status (false). - **message** (string) - The error message. - **statusCode** (number) - The HTTP status code. - **statusText** (string) - The standard HTTP status text. - **stack** (string) - Error stack trace (included only in development environments). ```