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.

Source
npmnpm
Version
3.1.0
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 duck-typed 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.statusMessage); // "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

All type guards use duck typing and return interface types (IHTTPError, IClientError, IServerError). They work with any object that has the right shape, not just instanceof checks.

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 statusMessage?: string;   // ASCII printable, max 256 chars
    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 (100-599). Invalid values default to 500.
statusCodenumber | stringDeprecated. Alias for status.
statusMessagestringReason phrase. Sanitized to ASCII printable, max 256 chars.
redirectURLstringRedirect URL for 3xx-style responses.

Plus all fields from @ebec/core ErrorOptions.

Type Guards

FunctionReturnsChecks
isHTTPError(input)input is IHTTPErrorstatus 400-599, passes isBaseError
isClientError(input)input is IClientErrorisHTTPError + status 400-499
isServerError(input)input is IServerErrorisHTTPError + 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 (100-599), defaults to 500
sanitizeStatusMessage(input)Strips non-ASCII, trims, caps at 256 chars
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 09 Apr 2026

Related posts