@b9g/http-errors

HTTP error classes for consistent error handling.


HTTPError

Base class for all HTTP errors.

Constructor

new HTTPError(status: number, message?: string, options?: HTTPErrorOptions)

HTTPErrorOptions

interface HTTPErrorOptions {
  cause?: Error;
  headers?: Record<string, string>;
  expose?: boolean;
}

Properties

PropertyTypeDescription
statusnumberHTTP status code
statusCodenumberAlias for status
messagestringError message
exposebooleanExpose message to clients
headersRecord<string, string>Custom headers
causeErrorOriginal error

toJSON(): object

Serializes the error.

error.toJSON();
// { name, message, status, statusCode, expose }

toResponse(isDev?: boolean): Response

Converts to HTTP Response.

error.toResponse();      // Plain text
error.toResponse(true);  // HTML with stack trace

Client Errors (4xx)

ClassStatusDefault Message
BadRequest400Bad Request
Unauthorized401Unauthorized
Forbidden403Forbidden
NotFound404Not Found
MethodNotAllowed405Method Not Allowed
Conflict409Conflict
UnprocessableEntity422Unprocessable Entity
TooManyRequests429Too Many Requests

Server Errors (5xx)

ClassStatusDefault Message
InternalServerError500Internal Server Error
NotImplemented501Not Implemented
BadGateway502Bad Gateway
ServiceUnavailable503Service Unavailable
GatewayTimeout504Gateway Timeout

isHTTPError(value: unknown): value is HTTPError

Type guard for HTTP errors.

if (isHTTPError(error)) {
  console.log(error.status);
}

Usage

import { NotFound, BadRequest } from "@b9g/http-errors";

throw new NotFound("User not found");

throw new BadRequest("Invalid email", {
  headers: { "X-Error-Code": "INVALID_EMAIL" },
});

Exposure

4xx errors expose messages by default; 5xx errors don't.

throw new BadRequest("Invalid input");  // Exposed
throw new InternalServerError("DB failed");  // Hidden

throw new InternalServerError("Overloaded", { expose: true });  // Override

See Also