A TypeScript library that provides a comprehensive set of HTTP error classes and utilities for handling HTTP errors in your applications.
- 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
npm i http-sentinel
-
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)
-
InternalServer
(500) -
NotImplemented
(501) -
BadGateway
(502) -
ServiceUnavailable
(503) -
GatewayTimeout
(504) -
HTTPVersionNotSupported
(505) -
VariantAlsoNegotiates
(506) -
InsufficientStorage
(507) -
LoopDetected
(508) -
NotExtended
(510) -
NetworkAuthenticationRequired
(511)
This reference describes the components exposed by Core()
in English, in tabular format, with usage examples.
Provide a quick guide to develop and handle custom HTTP errors using the object returned by Core()
.
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.
Returns an object with four main groups: throw, collections, tools, and create.
Error Name | Optional Parameter | What it does | Example |
---|---|---|---|
BadRequest |
message?: HttpErrorMessage |
Throws a 400 error. | stn.throw.BadRequest('Missing parameters') |
... | ... | ... | ... |
UnknownError |
message?: HttpErrorMessage |
Throws a generic uncategorized error. | stn.throw.UnknownError() |
Property | Description | Example Usage |
---|---|---|
BadRequest , Unauthorized , ..., UnknownError
|
Specific HTTP error classes. | if (error instanceof stn.collections.NotFound) { ... } |
Function | Parameters | Returns | Description | Example |
---|---|---|---|---|
resolveHttpError |
statusCode: number |
Throws | Maps an HTTP numeric code to its corresponding error and throws it. | stn.tools.resolveHttpError(404) |
compare |
caughtError: unknown , target: ErrorConstructor
|
boolean |
Checks if the caught error matches a specific HTTP error class. | stn.tools.compare(err, stn.collections.BadRequest) |
matches |
err: unknown |
boolean |
Detects if the error was created by http-sentinel's base structure. | if (stn.tools.matches(err)) { /* handle */ } |
Property | Description | Example |
---|---|---|
customError |
Creates 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)
|
import { stn } from "http-sentinel"
const status = 403
try {
stn.tools.resolveHttpError(status);
} catch (e) {
if (stn.tools.matches(e)) {
// uniform handling
}
}
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');
}
}
import { stn } from "http-sentinel"
const MyError = stn.create.customError('MyError', 'Something strange happened');
throw new MyError('Custom thrown');
- 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 intry/catch
. -
collections
provides the class references forinstanceof
checks and for passing tocompare
. -
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
, andExpectedError
types provide strong typing for status codes, messages, and known error instances.
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);
}
To run your tests in CI mode and generate a coverage report, use:
npm run test:ci