http-errors

repository·master·Indexed 23 days ago

https://github.com/jshttp/http-errors

A 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.

Tokens
1.7K
Snippets
5
Records
12
Agent score
32%

What's inside http-errors

  1. Create HTTP errors for Express middleware

    master

    You 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()
    })
  2. Extend an existing error with createError(status, error, properties)

    master

    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)
        }
      }
    })
  3. Create a new error with createError(status, message, properties)

    master

    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!')
  4. Create errors using named constructors

    master

    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()
  5. Check if a value is an HTTP error with createError.isHttpError(val)

    master
    Determines if the provided 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.
  6. Reference: Named HTTP Error Constructors

    master

    The following constructors are available for creating specific HTTP errors using the new createError.ConstructorName() pattern:

    Status CodeConstructor Name
    400BadRequest
    401Unauthorized
    402PaymentRequired
    403Forbidden
    404NotFound
    405MethodNotAllowed
    406NotAcceptable
    407ProxyAuthenticationRequired
    408RequestTimeout
    409Conflict
    410Gone
    411LengthRequired
    412PreconditionFailed
    413PayloadTooLarge
    414URITooLong
    415UnsupportedMediaType
    416RangeNotSatisfiable
    417ExpectationFailed
    418ImATeapot
    421MisdirectedRequest
    422UnprocessableEntity
    423Locked
    424FailedDependency
    425TooEarly
    426UpgradeRequired
    428PreconditionRequired
    429TooManyRequests
    431RequestHeaderFieldsTooLarge
    451UnavailableForLegalReasons
    500InternalServerError
    501NotImplemented
    502BadGateway
    503ServiceUnavailable
    504GatewayTimeout
    505HTTPVersionNotSupported
    506VariantAlsoNegotiates
    507InsufficientStorage
    508LoopDetected
    509BandwidthLimitExceeded
    510NotExtended
    511NetworkAuthenticationRequired
  7. HTTP Error Properties

    master

    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.
  8. Check if a value is an HTTP error using isHttpError()

    master

    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:

    1. It is an instance of HttpError.
    2. OR it is an Error object that has an expose property (boolean), a statusCode property (number), and where status === statusCode.
  9. Use specific HTTP error constructors

    master

    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.

    • 4xx Errors: These are treated as client errors and have expose: true.
    • 5xx Errors: These are treated as server errors and have expose: false.
  10. Create HTTP errors with createError()

    master

    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.

    Supported Argument Patterns

    1. Status and Message: createError(status, message, properties)
    2. Wrapping an existing Error: createError(error, properties) (The status is extracted from error.status or error.statusCode)
    3. Status only: createError(status)
    4. Message only: createError(message) (Defaults to status 500)
    5. Properties only: createError(properties) (Defaults to status 500)

    Error Properties

    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.
    • Custom Properties: Any properties passed in the properties object are merged into the error object (excluding status and statusCode).
  11. Access the HttpError base class

    master

    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.