Install http-errors via npm
masterInstall the http-errors module using the npm registry.
$ npm install http-errorsrepository·master·Indexed 23 days ago
https://github.com/jshttp/http-errorsA utility for creating HTTP error objects compatible with Express, Koa, Connect, and other Node.js web frameworks. It provides a flexible createError factory and named constructors for specific HTTP status codes (e.g., NotFound, InternalServerError) to generate error objects with appropriate status codes, messages, and custom properties.
Install the http-errors module using the npm registry.
$ npm install http-errorsYou can use http-errors within Express middleware to trigger error handling by passing a created error to the next() function.
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()
})Extends an existing error object with createError.HttpError properties. This does not change the inheritance of the original error object; it simply attaches the HTTP properties and returns the modified error.
status: The status code as a number.error: The existing error object to extend.properties: An object containing custom properties to attach.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)
}
}
})Creates a new error object that inherits from createError.HttpError.
status: The status code as a number.message: The error message. If omitted, it defaults to the standard Node.js text for that status code.properties: An object containing custom properties to attach to the error object.var err = createError(404, 'This video does not exist!')You can create specific HTTP errors using named constructors available on the createError object. These constructors inherit from createError.HttpError.
Example usage:
var err = new createError.NotFound()val is an HttpError. It returns true if the value inherits from createError.HttpError or matches the "duck type" of an error created by this module. Note that all outputs from the createError factory will return true for this function.The following constructors are available for creating specific HTTP errors using the new createError.ConstructorName() pattern:
| Status Code | Constructor Name |
|---|---|
| 400 | BadRequest |
| 401 | Unauthorized |
| 402 | PaymentRequired |
| 403 | Forbidden |
| 404 | NotFound |
| 405 | MethodNotAllowed |
| 406 | NotAcceptable |
| 407 | ProxyAuthenticationRequired |
| 408 | RequestTimeout |
| 409 | Conflict |
| 410 | Gone |
| 411 | LengthRequired |
| 412 | PreconditionFailed |
| 413 | PayloadTooLarge |
| 414 | URITooLong |
| 415 | UnsupportedMediaType |
| 416 | RangeNotSatisfiable |
| 417 | ExpectationFailed |
| 418 | ImATeapot |
| 421 | MisdirectedRequest |
| 422 | UnprocessableEntity |
| 423 | Locked |
| 424 | FailedDependency |
| 425 | TooEarly |
| 426 | UpgradeRequired |
| 428 | PreconditionRequired |
| 429 | TooManyRequests |
| 431 | RequestHeaderFieldsTooLarge |
| 451 | UnavailableForLegalReasons |
| 500 | InternalServerError |
| 501 | NotImplemented |
| 502 | BadGateway |
| 503 | ServiceUnavailable |
| 504 | GatewayTimeout |
| 505 | HTTPVersionNotSupported |
| 506 | VariantAlsoNegotiates |
| 507 | InsufficientStorage |
| 508 | LoopDetected |
| 509 | BandwidthLimitExceeded |
| 510 | NotExtended |
| 511 | NetworkAuthenticationRequired |
Every error object created by http-errors contains the following properties:
expose: A boolean indicating if the message should be sent to the client. Defaults to false when status >= 500.headers: An object of header names to values to be sent to the client (e.g., { 'www-authenticate': '...' }). Keys must be lower-cased. Defaults to undefined.message: The error message string.status: The HTTP status code.statusCode: The HTTP status code (mirrors status for compatibility). Defaults to 500.Use isHttpError(val) to determine if a given value is a valid HTTP error object produced by this library.
A value is considered an HTTP error if:
HttpError.Error object that has an expose property (boolean), a statusCode property (number), and where status === statusCode.The createError module exports specific constructors for every HTTP status code and their corresponding message identifiers. This allows you to use new to create specific error types.
For example, if the status 404 has the message Not Found, you can use createError[404] or createError.NotFound to instantiate the error.
expose: true.expose: false.The createError function is the primary way to generate HTTP error objects. It is highly flexible and supports several argument patterns to handle status codes, messages, existing error objects, and additional properties.
createError(status, message, properties)createError(error, properties) (The status is extracted from error.status or error.statusCode)createError(status)createError(message) (Defaults to status 500)createError(properties) (Defaults to status 500)When an error is created, the following properties are automatically attached:
status: The HTTP status code.statusCode: Identical to status.expose: A boolean indicating if the error should be exposed to the client. This is true for 4xx (client) errors and false for 5xx (server) errors.properties object are merged into the error object (excluding status and statusCode).The HttpError property on the exported module is an abstract base class that inherits from Error. It is used for type checking via instanceof.
Note: You cannot instantiate HttpError directly; attempting to do so will throw a TypeError.