### Installation Source: https://github.com/jshttp/http-errors/blob/master/README.md Install the http-errors module using npm. ```APIDOC ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```console $ npm install http-errors ``` ``` -------------------------------- ### Basic Usage Example Source: https://github.com/jshttp/http-errors/blob/master/README.md An example demonstrating how to use http-errors within an Express application. ```APIDOC ## Example ```js var createError = require('http-errors') var express = require('express') var app = express() app.use(function (req, res, next) { if (!req.user) return next(createError(401, 'Please login to view this page.')) next() }) ``` ``` -------------------------------- ### Install http-errors Source: https://github.com/jshttp/http-errors/blob/master/README.md Install the http-errors module using npm. This is a Node.js module. ```bash $ npm install http-errors ``` -------------------------------- ### Express Integration Example Source: https://context7.com/jshttp/http-errors/llms.txt Demonstrates how to use http-errors within an Express application for authentication, authorization, resource lookup, input validation, and centralized error handling. ```javascript var createError = require('http-errors') var express = require('express') var app = express() // Authentication middleware app.use(function (req, res, next) { if (!req.headers.authorization) { return next(createError(401, 'Please login to view this page')) } next() }) // Route with authorization check app.get('/admin', function (req, res, next) { if (!req.user.isAdmin) { return next(createError(403, 'Admin access required')) } res.json({ data: 'admin data' }) }) // Route with resource lookup app.get('/users/:id', function (req, res, next) { var user = findUser(req.params.id) if (!user) { return next(createError(404, 'User not found', { userId: req.params.id })) } res.json(user) }) // Route with validation app.post('/users', function (req, res, next) { if (!req.body.email) { return next(createError(422, 'Email is required', { field: 'email', code: 'MISSING_FIELD' })) } // create user... }) // Error handling middleware app.use(function (err, req, res, next) { res.status(err.status || 500) res.json({ error: { message: err.expose ? err.message : 'Internal Server Error', status: err.status || 500, ...(err.field && { field: err.field }), ...(err.code && { code: err.code }) } }) }) app.listen(3000) ``` -------------------------------- ### Create HTTP errors using named constructors with createError Source: https://context7.com/jshttp/http-errors/llms.txt Instantiate specific HTTP errors using named constructors like `createError.NotFound` or numeric accessors like `createError[404]`. These constructors accept an optional message. Client errors (4xx) default to `expose: true`, while server errors (5xx) default to `expose: false`. ```javascript var createError = require('http-errors') // Using named constructors var err = new createError.NotFound() console.log(err.status) // 404 console.log(err.message) // "Not Found" console.log(err.name) // "NotFoundError" var err = new createError.NotFound('User profile not found') console.log(err.message) // "User profile not found" // Using numeric code access var err = new createError[404]() console.log(err.status) // 404 var err = new createError[500]('Database timeout') console.log(err.message) // "Database timeout" console.log(err.expose) // false // Common client errors (4xx) - expose: true by default var badRequest = new createError.BadRequest('Invalid JSON') var unauthorized = new createError.Unauthorized('Please login') var forbidden = new createError.Forbidden('Access denied') var notFound = new createError.NotFound('Page not found') var conflict = new createError.Conflict('Resource already exists') var unprocessable = new createError.UnprocessableEntity('Validation failed') var tooMany = new createError.TooManyRequests('Rate limit exceeded') // Common server errors (5xx) - expose: false by default var internal = new createError.InternalServerError() var notImplemented = new createError.NotImplemented('Feature coming soon') var badGateway = new createError.BadGateway() var unavailable = new createError.ServiceUnavailable('Maintenance mode') var timeout = new createError.GatewayTimeout() // instanceof checks console.log(err instanceof Error) // true console.log(err instanceof createError.HttpError) // true console.log(err instanceof createError.NotFound) // true ``` -------------------------------- ### Create Server Error (5xx) Source: https://context7.com/jshttp/http-errors/llms.txt When creating server errors (5xx), the `expose` property defaults to `false`, preventing the message from being sent to the client. ```javascript var createError = require('http-errors') // Server error (5xx) - expose defaults to false var err = createError(500, 'Database connection failed') console.log(err.expose) // false (server errors hide message from client) ``` -------------------------------- ### Create Error with Properties Only Source: https://context7.com/jshttp/http-errors/llms.txt Passing an object as the sole argument to `createError` creates a 500 Internal Server Error with the provided properties. ```javascript var createError = require('http-errors') // Just properties (defaults to 500) var err = createError({ id: 1, details: 'validation failed' }) console.log(err.status) // 500 console.log(err.id) // 1 ``` -------------------------------- ### HTTP Error Properties Reference Source: https://context7.com/jshttp/http-errors/llms.txt Illustrates the standard properties of HTTP errors created by the library, including message, status, expose, name, and custom headers. ```javascript var createError = require('http-errors') // Client error (4xx) properties var clientErr = createError(404, 'Resource not found') console.log({ message: clientErr.message, // "Resource not found" status: clientErr.status, // 404 statusCode: clientErr.statusCode, // 404 (alias for status) expose: clientErr.expose, // true (safe to send to client) name: clientErr.name, // "NotFoundError" stack: clientErr.stack // Full stack trace }) // Server error (5xx) properties var serverErr = createError(500, 'Database connection failed') console.log({ message: serverErr.message, // "Database connection failed" status: serverErr.status, // 500 statusCode: serverErr.statusCode, // 500 expose: serverErr.expose, // false (hide from client) name: serverErr.name, // "InternalServerError" stack: serverErr.stack // Full stack trace }) // Custom headers property (for WWW-Authenticate, Retry-After, etc.) var authErr = createError(401, 'Invalid token', { headers: { 'www-authenticate': 'Bearer realm="api"' } }) console.log(authErr.headers) // { 'www-authenticate': 'Bearer realm="api"' } // Override expose for sensitive client errors var sensitiveErr = createError(400, 'SQL injection detected', { expose: false }) console.log(sensitiveErr.expose) // false ``` -------------------------------- ### HTTP Error Constructors Source: https://github.com/jshttp/http-errors/blob/master/README.md The http-errors package provides constructors for a wide range of HTTP status codes. Each constructor can be used to create an error object corresponding to a specific HTTP error. ```APIDOC ## HTTP Error Constructors ### Description This section lists all available constructors for creating HTTP errors. Each constructor is mapped to a specific HTTP status code. ### Constructors #### 400 Bad Request - **Constructor Name**: `BadRequest` #### 401 Unauthorized - **Constructor Name**: `Unauthorized` #### 402 Payment Required - **Constructor Name**: `PaymentRequired` #### 403 Forbidden - **Constructor Name**: `Forbidden` #### 404 Not Found - **Constructor Name**: `NotFound` #### 405 Method Not Allowed - **Constructor Name**: `MethodNotAllowed` #### 406 Not Acceptable - **Constructor Name**: `NotAcceptable` #### 407 Proxy Authentication Required - **Constructor Name**: `ProxyAuthenticationRequired` #### 408 Request Timeout - **Constructor Name**: `RequestTimeout` #### 409 Conflict - **Constructor Name**: `Conflict` #### 410 Gone - **Constructor Name**: `Gone` #### 411 Length Required - **Constructor Name**: `LengthRequired` #### 412 Precondition Failed - **Constructor Name**: `PreconditionFailed` #### 413 Payload Too Large - **Constructor Name**: `PayloadTooLarge` #### 414 URI Too Long - **Constructor Name**: `URITooLong` #### 415 Unsupported Media Type - **Constructor Name**: `UnsupportedMediaType` #### 416 Range Not Satisfiable - **Constructor Name**: `RangeNotSatisfiable` #### 417 Expectation Failed - **Constructor Name**: `ExpectationFailed` #### 418 I'm a teapot - **Constructor Name**: `ImATeapot` #### 421 Misdirected Request - **Constructor Name**: `MisdirectedRequest` #### 422 Unprocessable Entity - **Constructor Name**: `UnprocessableEntity` #### 423 Locked - **Constructor Name**: `Locked` #### 424 Failed Dependency - **Constructor Name**: `FailedDependency` #### 425 Too Early - **Constructor Name**: `TooEarly` #### 426 Upgrade Required - **Constructor Name**: `UpgradeRequired` #### 428 Precondition Required - **Constructor Name**: `PreconditionRequired` #### 429 Too Many Requests - **Constructor Name**: `TooManyRequests` #### 431 Request Header Fields Too Large - **Constructor Name**: `RequestHeaderFieldsTooLarge` #### 451 Unavailable For Legal Reasons - **Constructor Name**: `UnavailableForLegalReasons` #### 500 Internal Server Error - **Constructor Name**: `InternalServerError` #### 501 Not Implemented - **Constructor Name**: `NotImplemented` #### 502 Bad Gateway - **Constructor Name**: `BadGateway` #### 503 Service Unavailable - **Constructor Name**: `ServiceUnavailable` #### 504 Gateway Timeout - **Constructor Name**: `GatewayTimeout` #### 505 HTTP Version Not Supported - **Constructor Name**: `HTTPVersionNotSupported` #### 506 Variant Also Negotiates - **Constructor Name**: `VariantAlsoNegotiates` #### 507 Insufficient Storage - **Constructor Name**: `InsufficientStorage` #### 508 Loop Detected - **Constructor Name**: `LoopDetected` #### 509 Bandwidth Limit Exceeded - **Constructor Name**: `BandwidthLimitExceeded` #### 510 Not Extended - **Constructor Name**: `NotExtended` #### 511 Network Authentication Required - **Constructor Name**: `NetworkAuthenticationRequired` ### Usage Example ```javascript const createError = require('http-errors'); // Create a 404 Not Found error const notFoundError = createError(404); // Create a 500 Internal Server Error with a message const internalError = createError(500, 'Something went wrong!'); // Create a custom error with properties const customError = createError(400, 'Invalid input', { details: 'The provided data is not in the expected format.' }); console.error(notFoundError); console.error(internalError); console.error(customError); ``` ``` -------------------------------- ### createError[code]() / createError[Name]() Source: https://context7.com/jshttp/http-errors/llms.txt Creates HTTP errors using named constructors for specific status codes or PascalCase names. Accepts an optional custom message. ```APIDOC ## new createError[code]() / new createError[Name]() ### Description Creates HTTP errors using named constructors for specific status codes. Available as both numeric codes (`createError[404]`) and PascalCase names (`createError.NotFound`). All constructors accept an optional custom message. ### Usage ```javascript var createError = require('http-errors') // Using named constructors var err = new createError.NotFound() console.log(err.status) // 404 console.log(err.message) // "Not Found" console.log(err.name) // "NotFoundError" var err = new createError.NotFound('User profile not found') console.log(err.message) // "User profile not found" // Using numeric code access var err = new createError[404]() console.log(err.status) // 404 var err = new createError[500]('Database timeout') console.log(err.message) // "Database timeout" console.log(err.expose) // false // Common client errors (4xx) - expose: true by default var badRequest = new createError.BadRequest('Invalid JSON') var unauthorized = new createError.Unauthorized('Please login') var forbidden = new createError.Forbidden('Access denied') var notFound = new createError.NotFound('Page not found') var conflict = new createError.Conflict('Resource already exists') var unprocessable = new createError.UnprocessableEntity('Validation failed') var tooMany = new createError.TooManyRequests('Rate limit exceeded') // Common server errors (5xx) - expose: false by default var internal = new createError.InternalServerError() var notImplemented = new createError.NotImplemented('Feature coming soon') var badGateway = new createError.BadGateway() var unavailable = new createError.ServiceUnavailable('Maintenance mode') var timeout = new createError.GatewayTimeout() // instanceof checks console.log(err instanceof Error) // true console.log(err instanceof createError.HttpError) // true console.log(err instanceof createError.NotFound) // true ``` ``` -------------------------------- ### Create a NotFound error instance Source: https://github.com/jshttp/http-errors/blob/master/README.md Instantiate a specific HTTP error type, such as NotFound, using the new keyword. The error object inherits from createError.HttpError. ```javascript var err = new createError.NotFound() ``` -------------------------------- ### Create HTTP Error with Status Code Source: https://context7.com/jshttp/http-errors/llms.txt Use `createError` with a status code to generate a standard HTTP error. Client errors (4xx) have `expose: true` by default. ```javascript var createError = require('http-errors') // Basic usage with status code var err = createError(404) console.log(err.message) // "Not Found" console.log(err.status) // 404 console.log(err.statusCode) // 404 console.log(err.expose) // true (client errors expose message) ``` -------------------------------- ### Create Error with Message Only Source: https://context7.com/jshttp/http-errors/llms.txt If only a message string is provided to `createError`, it defaults to a 500 Internal Server Error status. ```javascript var createError = require('http-errors') // Just message (defaults to 500) var err = createError('Something went wrong') console.log(err.status) // 500 console.log(err.message) // "Something went wrong" ``` -------------------------------- ### HttpError Source: https://context7.com/jshttp/http-errors/llms.txt The abstract base class for all HTTP errors. Useful for `instanceof` checks. ```APIDOC ## createError.HttpError ### Description The abstract base class that all HTTP errors inherit from. Cannot be instantiated directly but useful for `instanceof` checks. ### Usage ```javascript var createError = require('http-errors') // Cannot instantiate directly try { new createError.HttpError() } catch (e) { console.log(e.message) // "cannot construct abstract class" } // Use for type checking var err = createError(404) console.log(err instanceof createError.HttpError) // true var regularErr = new Error('normal error') console.log(regularErr instanceof createError.HttpError) // false // In error handling middleware function errorHandler(err, req, res, next) { if (err instanceof createError.HttpError) { // Handle HTTP errors with their status res.status(err.status) if (err.expose) { res.json({ error: err.message }) } else { res.json({ error: 'An error occurred' }) } } else { // Handle unexpected errors as 500 res.status(500).json({ error: 'Internal Server Error' }) } } ``` ``` -------------------------------- ### createError([status], [message], [properties]) Source: https://github.com/jshttp/http-errors/blob/master/README.md Creates a new error object with a status code, message, and custom properties. ```APIDOC ### createError([status], [message], [properties]) Create a new error object with the given message `msg`. The error object inherits from `createError.HttpError`. ```js var err = createError(404, 'This video does not exist!') ``` - `status: 500` - the status code as a number - `message` - the message of the error, defaulting to node's text for that status code. - `properties` - custom properties to attach to the object ``` -------------------------------- ### new createError[code || name]([msg]) Source: https://github.com/jshttp/http-errors/blob/master/README.md Creates a new HTTP error object using a status code or error name. ```APIDOC ### new createError[code || name]([msg]) Create a new error object with the given message `msg`. The error object inherits from `createError.HttpError`. ```js var err = new createError.NotFound() ``` - `code` - the status code as a number - `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. ``` -------------------------------- ### createError([status], [error], [properties]) Source: https://github.com/jshttp/http-errors/blob/master/README.md Extends an existing error object with HTTP error properties. ```APIDOC ### createError([status], [error], [properties]) Extend the given `error` object with `createError.HttpError` properties. This will not alter the inheritance of the given `error` object, and the modified `error` object is the return value. ```js fs.readFile('foo.txt', function (err, buf) { if (err) { if (err.code === 'ENOENT') { var httpError = createError(404, err, { expose: false }) } else { var httpError = createError(500, err) } } }) ``` - `status` - the status code as a number - `error` - the error object to extend - `properties` - custom properties to attach to the object ``` -------------------------------- ### Create a 404 error with a custom message Source: https://github.com/jshttp/http-errors/blob/master/README.md Create a new HTTP error object with a specific status code and a custom message. The error object inherits from createError.HttpError. ```javascript var err = createError(404, 'This video does not exist!') ``` -------------------------------- ### Create HTTP Error with Custom Message Source: https://context7.com/jshttp/http-errors/llms.txt Provide a custom message string to `createError` along with the status code. The error name will reflect the status code (e.g., 'NotFoundError'). ```javascript var createError = require('http-errors') // With custom message var err = createError(404, 'This video does not exist!') console.log(err.message) // "This video does not exist!" console.log(err.name) // "NotFoundError" ``` -------------------------------- ### Extend Error with Pre-set Status Source: https://context7.com/jshttp/http-errors/llms.txt When extending an existing error that already has a `status` property, `createError` will use that status code. ```javascript var createError = require('http-errors') // Extending error with custom status already set var originalErr = new Error('User not authorized') originalErr.status = 403 var httpError = createError(originalErr) console.log(httpError.status) // 403 (uses existing status) console.log(httpError.statusCode) // 403 console.log(httpError.expose) // true (4xx error) ``` -------------------------------- ### Create HTTP Error with Custom Properties Source: https://context7.com/jshttp/http-errors/llms.txt Add custom properties to an HTTP error object by passing a third argument to `createError`. These properties are merged into the error object. ```javascript var createError = require('http-errors') // With custom properties var err = createError(404, 'Resource not found', { id: 'video-123', type: 'video' }) console.log(err.id) // "video-123" console.log(err.type) // "video" ``` -------------------------------- ### Error Properties Source: https://github.com/jshttp/http-errors/blob/master/README.md Details about the properties available on error objects created by http-errors. ```APIDOC ### Error Properties - `expose` - can be used to signal if `message` should be sent to the client, defaulting to `false` when `status` >= 500 - `headers` - can be an object of header names to values to be sent to the client, defaulting to `undefined`. When defined, the key names should all be lower-cased - `message` - the traditional error message, which should be kept short and all single line - `status` - the status code of the error, mirroring `statusCode` for general compatibility - `statusCode` - the status code of the error, defaulting to `500` ``` -------------------------------- ### Extend Existing Error with HTTP Properties Source: https://context7.com/jshttp/http-errors/llms.txt Use `createError` with an existing Error object as the second argument to add HTTP properties without changing its prototype. This preserves original error details like `code`. ```javascript var createError = require('http-errors') var fs = require('fs') // Extending a file system error fs.readFile('nonexistent.txt', function (err, buf) { if (err) { if (err.code === 'ENOENT') { // Convert to 404 Not Found var httpError = createError(404, err, { expose: false }) console.log(httpError.status) // 404 console.log(httpError.message) // "ENOENT: no such file or directory..." console.log(httpError.code) // "ENOENT" (original property preserved) console.log(httpError === err) // true (same object, extended) } else { // Convert to 500 Internal Server Error var httpError = createError(500, err) console.log(httpError.expose) // false } } }) ``` -------------------------------- ### Extend an existing error object with HTTP error properties Source: https://github.com/jshttp/http-errors/blob/master/README.md Extend a given error object with http-errors properties. This is useful when handling existing errors that need to be converted into HTTP errors. The original error object is modified and returned. ```javascript fs.readFile('foo.txt', function (err, buf) { if (err) { if (err.code === 'ENOENT') { var httpError = createError(404, err, { expose: false }) } else { var httpError = createError(500, err) } } }) ``` -------------------------------- ### Check if an error inherits from createError.HttpError Source: https://context7.com/jshttp/http-errors/llms.txt Use `instanceof createError.HttpError` to check if an error object is an instance of the base HTTP error class provided by the `http-errors` module. This is useful in error handling to apply specific logic for HTTP errors. ```javascript var createError = require('http-errors') // Cannot instantiate directly try { new createError.HttpError() } catch (e) { console.log(e.message) // "cannot construct abstract class" } // Use for type checking var err = createError(404) console.log(err instanceof createError.HttpError) // true var regularErr = new Error('normal error') console.log(regularErr instanceof createError.HttpError) // false // In error handling middleware function errorHandler(err, req, res, next) { if (err instanceof createError.HttpError) { // Handle HTTP errors with their status res.status(err.status) if (err.expose) { res.json({ error: err.message }) } else { res.json({ error: 'An error occurred' }) } } else { // Handle unexpected errors as 500 res.status(500).json({ error: 'Internal Server Error' }) } } ``` -------------------------------- ### Check if a value is an HTTP error using createError.isHttpError() Source: https://context7.com/jshttp/http-errors/llms.txt Use `createError.isHttpError(val)` to determine if a value is an instance of an HTTP error created by this module or if it matches the expected properties of an HTTP error. This is useful in error handling middleware to differentiate between HTTP-specific errors and other types of errors. ```javascript var createError = require('http-errors') // Check errors created by createError var err = createError(404) console.log(createError.isHttpError(err)) // true // Check extended errors var extendedErr = createError(500, new Error('Original error')) console.log(createError.isHttpError(extendedErr)) // true // Check non-HTTP errors console.log(createError.isHttpError(new Error('plain error'))) // false console.log(createError.isHttpError(null)) // false console.log(createError.isHttpError(undefined)) // false console.log(createError.isHttpError({})) // false console.log(createError.isHttpError('error string')) // false console.log(createError.isHttpError(404)) // false // Use in error handling middleware function errorHandler(err, req, res, next) { if (createError.isHttpError(err)) { res.status(err.status).json({ error: err.expose ? err.message : 'Internal Server Error' }) } else { res.status(500).json({ error: 'Internal Server Error' }) } } ``` -------------------------------- ### isHttpError(val) Source: https://context7.com/jshttp/http-errors/llms.txt Checks if a value is an HTTP error, either by inheritance from HttpError or by duck typing. ```APIDOC ## isHttpError(val) ### Description Determines if the provided value is an HTTP error. Returns `true` if the error inherits from `HttpError` or matches the "duck type" signature (an Error with `expose` boolean, `statusCode` number, and `status === statusCode`). ### Usage ```javascript var createError = require('http-errors') // Check errors created by createError var err = createError(404) console.log(createError.isHttpError(err)) // true // Check extended errors var extendedErr = createError(500, new Error('Original error')) console.log(createError.isHttpError(extendedErr)) // true // Check non-HTTP errors console.log(createError.isHttpError(new Error('plain error'))) // false console.log(createError.isHttpError(null)) // false console.log(createError.isHttpError(undefined)) // false console.log(createError.isHttpError({})) // false console.log(createError.isHttpError('error string')) // false console.log(createError.isHttpError(404)) // false // Use in error handling middleware function errorHandler(err, req, res, next) { if (createError.isHttpError(err)) { res.status(err.status).json({ error: err.expose ? err.message : 'Internal Server Error' }) } else { res.status(500).json({ error: 'Internal Server Error' }) } } ``` ``` -------------------------------- ### Override Status on Existing Error Source: https://context7.com/jshttp/http-errors/llms.txt You can override the status code of an existing error by providing a new status code as the first argument to `createError` when extending it. ```javascript var createError = require('http-errors') // Override status on existing error var err = new Error('Resource locked') var httpError = createError(423, err, { resource: '/api/data' }) console.log(httpError.status) // 423 console.log(httpError.resource) // "/api/data" ``` -------------------------------- ### createError.isHttpError(val) Source: https://github.com/jshttp/http-errors/blob/master/README.md Checks if a value is an HTTP error object created by this module. ```APIDOC ### createError.isHttpError(val) Determine if the provided `val` is an `HttpError`. This will return `true` if the error inherits from the `HttpError` constructor of this module or matches the "duck type" for an error this module creates. All outputs from the `createError` factory will return `true` for this function, including if an non-`HttpError` was passed into the factory. ``` -------------------------------- ### Create an HTTP error in Express middleware Source: https://github.com/jshttp/http-errors/blob/master/README.md Use http-errors to create an error object within Express middleware. If a condition is met (e.g., user not logged in), call next() with the created error. ```javascript var createError = require('http-errors') var express = require('express') var app = express() app.use(function (req, res, next) { if (!req.user) return next(createError(401, 'Please login to view this page.')) next() }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.