New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

http-sentinel

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

http-sentinel

💥A TypeScript library that provides a comprehensive set of HTTP error classes and utilities for handling HTTP errors in your applications.

latest
Source
npmnpm
Version
1.0.13
Version published
Weekly downloads
13
-86.6%
Maintainers
1
Weekly downloads
 
Created
Source

HTTP Error Handling Library

A TypeScript library that provides a comprehensive set of HTTP error classes and utilities for handling HTTP errors in your applications.

banner

Table of Contents

Features

  • Complete set of HTTP error classes (4xx and 5xx status codes)
  • Type-safe error handling
  • Custom error messages support
  • Utility functions for error type checking
  • TypeScript support with full type definitions
  • Factory function for creating custom HTTP errors

Installation

npm i http-sentinel

Available Error Classes

4xx Client Errors

  • BadRequest (400)
  • Unauthorized (401)
  • PaymentRequired (402)
  • Forbidden (403)
  • NotFound (404)
  • MethodNotAllowed (405)
  • NotAcceptable (406)
  • ProxyAuthenticationRequired (407)
  • RequestTimeout (408)
  • Conflict (409)
  • Gone (410)
  • LengthRequired (411)
  • PreconditionFailed (412)
  • PayloadTooLarge (413)
  • URITooLong (414)
  • UnsupportedMediaType (415)
  • RangeNotSatisfiable (416)
  • ExpectationFailed (417)
  • ImATeapot (418)
  • MisdirectedRequest (421)
  • UnprocessableEntity (422)
  • Locked (423)
  • FailedDependency (424)
  • TooEarly (425)
  • UpgradeRequired (426)
  • PreconditionRequired (428)
  • TooManyRequests (429)
  • RequestHeaderFieldsTooLarge (431)
  • UnavailableForLegalReasons (451)

5xx Server Errors

  • InternalServer (500)
  • NotImplemented (501)
  • BadGateway (502)
  • ServiceUnavailable (503)
  • GatewayTimeout (504)
  • HTTPVersionNotSupported (505)
  • VariantAlsoNegotiates (506)
  • InsufficientStorage (507)
  • LoopDetected (508)
  • NotExtended (510)
  • NetworkAuthenticationRequired (511)

API Reference: Core (http-sentinel)

This reference describes the components exposed by Core() in English, in tabular format, with usage examples.

Purpose

Provide a quick guide to develop and handle custom HTTP errors using the object returned by Core().

TypeScript Support

The library provides TypeScript type definitions for improved DX and type safety:

  • HttpStatusCode: a union type of valid HTTP status codes (e.g., 400 | 401 | 404 | 500 | ...).

  • HttpErrorMessage: can be either a plain string or a predefined set of messages provided by http-sentinel.

    • Predefined messages cover common HTTP error scenarios.
    • Allows any other string as a custom message.
  • ExpectedError: a union type of all standard error class instances provided by http-sentinel.

    • Represents the complete set of recognized error instances.
    • Useful for narrowing catch blocks and ensuring type safety when handling known errors.

1. Main Namespace: stn

Returns an object with four main groups: throw, collections, tools, and create.

1.1. throw (shortcut to throw HTTP errors)

Error NameOptional ParameterWhat it doesExample
BadRequestmessage?: HttpErrorMessageThrows a 400 error.stn.throw.BadRequest('Missing parameters')
............
UnknownErrormessage?: HttpErrorMessageThrows a generic uncategorized error.stn.throw.UnknownError()

1.2. collections

PropertyDescriptionExample Usage
BadRequest, Unauthorized, ..., UnknownErrorSpecific HTTP error classes.if (error instanceof stn.collections.NotFound) { ... }

1.3. tools

FunctionParametersReturnsDescriptionExample
resolveHttpErrorstatusCode: numberThrowsMaps an HTTP numeric code to its corresponding error and throws it.stn.tools.resolveHttpError(404)
comparecaughtError: unknown, target: ErrorConstructorbooleanChecks if the caught error matches a specific HTTP error class.stn.tools.compare(err, stn.collections.BadRequest)
matcheserr: unknownbooleanDetects if the error was created by http-sentinel's base structure.if (stn.tools.matches(err)) { /* handle */ }

1.4. create

PropertyDescriptionExample
customErrorCreates a custom or extended HTTP error based on http-sentinel's foundations. Status code is optional.stn.create.customError('MyError', 'customMessage') or stn.create.customError('MyError', 'customMessage', 422)

2. Common Examples

2.1. Resolve and throw by code

import { stn } from "http-sentinel"

const status = 403
try {
  stn.tools.resolveHttpError(status);
} catch (e) {
  if (stn.tools.matches(e)) {
    // uniform handling
  }
}

2.2. Compare caught errors

import { stn } from "http-sentinel"

try {
  stn.throw.NotFound('User not found');
} catch (err) {
  if (stn.tools.compare(err, stn.collections.NotFound)) {
    console.log('It is an explicit 404');
  }
}

2.3. Define a custom error

import { stn } from "http-sentinel"

const MyError = stn.create.customError('MyError', 'Something strange happened');
throw new MyError('Custom thrown');

3. Notes

  • Functions in throw always throw the error; they do not return a value. If you need to handle it without breaking the flow, wrap it in try/catch.
  • collections provides the class references for instanceof checks and for passing to compare.
  • matches is useful to filter out errors that are not part of the http-sentinel ecosystem and avoid false positives.
  • customError allows extension with additional metadata for traceability. The status code argument is optional.
  • TypeScript's HttpStatusCode, HttpErrorMessage, and ExpectedError types provide strong typing for status codes, messages, and known error instances.

4. Request

This library also includes a function to make HTTP requests to an API, automatically integrating error handling via http-sentinel utilities. It provides a simple and fast way to fetch data and manage any failures. It uses the same signature (parameters and options) as the native fetch function.

import { request } from "http-sentinel";

interface User {
  id: number;
  name: string;
  role: string;
}

// GET
const { success, data, error } = await request.get<User>({
  url: "/api/users/1",
  timeout: 5000
});

if (success && data) {
  console.log(data.name);       // Typed as User
  console.log(data.role);       
} else {
  // Manejo de errores estandarizado
  console.error("Error:", error?.message);
  console.error("Tipo:", error?.name);
  console.error("Código HTTP:", error?.statusCode);
}

Here’s an example of a POST request using the same http-sentinel API:

import { request } from "http-sentinel";

interface User {
  id: number;
  name: string;
  role: string;
}

interface CreateUserPayload {
  name: string;
  role: string;
}

const newUser: CreateUserPayload = {
  name: "Alice",
  role: "admin",
};


// POST request
const { success, data, error } = await request.post<User>(
  {
    url: "/api/users",
    options: { body: JSON.stringify(newUser) },
    timeout: 5000
  }
);

if (success && data) {
  console.log("Created user ID:", data.id);  // Typed as User
  console.log("Name:", data.name);
  console.log("Role:", data.role);
} else {
  // Standardized error handling
  console.error("Error:", error?.message);
  console.error("Type:", error?.name);
  console.error("HTTP Status Code:", error?.statusCode);
}

Test Coverage

To run your tests in CI mode and generate a coverage report, use:

npm run test:ci

Keywords

http

FAQs

Package last updated on 09 Aug 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts