New:Microsoft Teams Notifications Are Now Available in Socket.Learn more
Get Started

@ebec/http

Package Overview
Dependencies
Maintainers
1
Versions
31
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ebec/http

43 pre-built HTTP error classes (4xx/5xx) with status codes, status messages, and duck-typed type guards.

latest
Source
npmnpm
Version
4.3.2
Version published
Weekly downloads
871
-41.82%
Maintainers
1
Weekly downloads
 
Created
Source

@ebec/http 🌐

npm version main codecov

HTTP error classes for TypeScript, extending @ebec/core. Provides 43 pre-built error classes for HTTP 4xx and 5xx status codes with @instanceof-chain-based type guards.

Table of Contents

Installation

npm install @ebec/http

This installs @ebec/core as a dependency automatically.

Quick Start

import { NotFoundError, InternalServerError } from '@ebec/http';

// String message
const error = new NotFoundError('user not found');
console.log(error.status);        // 404
console.log(error.code);          // "NOT_FOUND"
console.log(error.message);       // "user not found"

// Options input
const error = new InternalServerError({
    message: 'database connection lost',
    code: 'DB_CONN_LOST',
});
console.log(error.status); // 500
console.log(error.code);   // "DB_CONN_LOST"

Use in an Express-style error handler:

import { isHTTPError } from '@ebec/http';

app.use((err, req, res, next) => {
    if (isHTTPError(err)) {
        res.status(err.status).json(err.toJSON());
    } else {
        res.status(500).json({ message: 'Internal Server Error' });
    }
});

Custom Subclasses

Extend any error class with your own defaults:

import { NotFoundError } from '@ebec/http';

class UserNotFoundError extends NotFoundError {
    constructor(userId: number) {
        super({
            message: `User ${userId} not found`,
            code: 'USER_NOT_FOUND',
        });
    }
}

throw new UserNotFoundError(42);
// status: 404, code: "USER_NOT_FOUND", message: "User 42 not found"

Type Guards

Type guards check the @instanceof class-marker chain and return interface types (IHTTPError, IClientError, IServerError). Identity is chain-only — there is no duck-typing shape fallback. An object that merely has the right shape (a status field, a code, even one carried over from another HTTP error library) is not recognised; only errors that actually carry the @ebec/http marker chain are.

isHTTPError matches via matchesInstanceof — as a Symbol.for(...) marker on in-process instances, or as the string list that toJSON() emits under the @instanceof key — so the match survives a JSON round-trip. isClientError and isServerError are status-range refinements, not separate identity checks: each first matches its own chain marker (so a NotFoundError matches isClientError outright), and otherwise delegates identity to isHTTPError and decides by status range from there. That's why a bare new HTTPError({ status: 404 }) — which never marks itself as a ClientError — still matches isClientError: it's a confirmed HTTPError by chain, refined by status.

import {
    isHTTPError,
    isClientError,
    isServerError,
} from '@ebec/http';

if (isHTTPError(error)) {
    // error has status (400-599)
    console.log(error.status);
}

if (isClientError(error)) {
    // error has status 400-499
}

if (isServerError(error)) {
    // error has status 500-599
}

Accessing Core Exports

Everything from @ebec/core is available via the ./core subpath:

import { BaseError, isBaseError } from '@ebec/http/core';

Error Classes

Base

ClassDescription
HTTPErrorBase HTTP error, extends BaseError. Defaults to status 500.
ClientErrorBase for 4xx errors, extends HTTPError.
ServerErrorBase for 5xx errors, extends HTTPError.

Client (4xx)

StatusClassCode
400BadRequestErrorBAD_REQUEST
401UnauthorizedErrorUNAUTHORIZED
403ForbiddenErrorFORBIDDEN
404NotFoundErrorNOT_FOUND
405MethodNotAllowedErrorMETHOD_NOT_ALLOWED
406NotAcceptableErrorNOT_ACCEPTABLE
407ProxyAuthenticationRequiredErrorPROXY_AUTHENTICATION_REQUIRED
408RequestTimeoutErrorREQUEST_TIMEOUT
409ConflictErrorCONFLICT
410GoneErrorGONE
411LengthRequiredErrorLENGTH_REQUIRED
412PreconditionFailedErrorPRECONDITION_FAILED
413RequestEntityTooLargeErrorREQUEST_ENTITY_TOO_LARGE
414RequestURITooLongErrorREQUEST_URI_TOO_LONG
415UnsupportedMediaTypeErrorUNSUPPORTED_MEDIA_TYPE
416RequestedRangeNotSatisfiableErrorREQUESTED_RANGE_NOT_SATISFIABLE
417ExpectationFailedErrorEXPECTATION_FAILED
418ImATeapotErrorIM_A_TEAPOT
420EnhanceYourCalmErrorENHANCE_YOUR_CALM
422UnprocessableEntityErrorUNPROCESSABLE_ENTITY
423LockedErrorLOCKED
424FailedDependencyErrorFAILED_DEPENDENCY
425UnorderedCollectionErrorUNORDERED_COLLECTION
426UpgradeRequiredErrorUPGRADE_REQUIRED
428PreconditionRequiredErrorPRECONDITION_REQUIRED
429TooManyRequestsErrorTOO_MANY_REQUESTS
431RequestHeaderFieldsTooLargeErrorREQUEST_HEADER_FIELDS_TOO_LARGE
444NoResponseErrorNO_RESPONSE
449RetryWithErrorRETRY_WITH
450BlockedByWindowsParentalControlsErrorBLOCKED_BY_WINDOWS_PARENTAL_CONTROLS
499ClientClosedRequestErrorCLIENT_CLOSED_REQUEST

Server (5xx)

StatusClassCode
500InternalServerErrorINTERNAL_SERVER_ERROR
501NotImplementedErrorNOT_IMPLEMENTED
502BadGatewayErrorBAD_GATEWAY
503ServiceUnavailableErrorSERVICE_UNAVAILABLE
504GatewayTimeoutErrorGATEWAY_TIMEOUT
505HTTPVersionNotSupportedErrorHTTP_VERSION_NOT_SUPPORTED
506VariantAlsoNegotiatesErrorVARIANT_ALSO_NEGOTIATES
507InsufficientStorageErrorINSUFFICIENT_STORAGE
508LoopDetectedErrorLOOP_DETECTED
509BandwidthLimitExceededErrorBANDWIDTH_LIMIT_EXCEEDED
510NotExtendedErrorNOT_EXTENDED
511NetworkAuthenticationRequiredErrorNETWORK_AUTHENTICATION_REQUIRED

API Reference

HTTPError

class HTTPError extends BaseError {
    readonly status: number;           // defaults to 500
    readonly redirectURL?: string;

    get statusCode(): number;          // @deprecated — alias for `status`

    constructor(input?: string | ErrorOptions);
}

ErrorOptions

Extends core ErrorOptions with HTTP-specific fields:

PropertyTypeDescription
statusnumber | stringHTTP status code (400-599). Invalid values default to 500.
statusCodenumber | stringDeprecated. Alias for status.
redirectURLstringRedirect URL for 3xx-style responses.

Plus all fields from @ebec/core ErrorOptions.

Type Guards

FunctionReturnsChecks
isHTTPError(input)input is IHTTPErrorChain-only: true iff the @instanceof chain carries the HTTPError marker. No shape/status fallback
isClientError(input)input is IClientErrorOwn chain marker match; otherwise delegates identity to isHTTPError (chain-confirmed) + status 400-499
isServerError(input)input is IServerErrorOwn chain marker match; otherwise delegates identity to isHTTPError (chain-confirmed) + status 500-599
isErrorOptions(input)input is ErrorOptionsValidates HTTP options shape

Utilities

FunctionDescription
getStatusText(statusCode)Returns the reason phrase for a given status code, or undefined if not found
sanitizeStatusCode(input)Parses and validates (400-599), defaults to 500
STATUS_TEXTSMap of status codes to reason phrases (e.g. 400 → "Bad Request")

License

Made with 💚

Published under MIT License.

Keywords

error

FAQs

Package last updated on 18 Aug 2026

Related posts