HTTP response errors with default message, stacktrace, instanceof, error cause support and more.
npm install @httpx/exceptionHTTP status errors with default message, instanceof, stack and nested error support.
Lightweight, typical usage between 500b and 1300b.
Includes convenience typeguards, optional contextual info and a built-in serializer
to cover cross-environments challenges (RSC, SSR...).








- π Usage by explicit named imports and/or status code.
- π If message not provided, defaults to http error message
- π Supports pre-defined contextual information.
- π Built-in serializer to allow cross-env uses (ssr, rsc, superjson, logs...).
- π Supports nested error through native Error.cause support.
- π Extends native Error class with stacktrace support.
- π No deps. Node, bun, edge and modern browsers compatibility,
``bash`
npm install @httpx/exception # via npm
yarn add @httpx/exception # via yarn
pnpm add @httpx/exception # via pnpm
π Official website, GitHub Readme or generated typedoc.
---
- Usage
- By named imports
- By status code
- Parameters
- Error context
- Properties
- Nested errors
- Static members
- Instanceof checks
- Class diagram
- Typeguards
- Instanceof alternatives
- isHttpErrorStatusCode
- Serializer
- JSON
- Serializable
- Default messages
- Non-official status codes
- Helpers
- isErrorWithErrorStatusCode
- isObjectWithErrorStatusCode
- About bundle
- Compatibility
- Bundle size
- Packaging
- Typescript
- Upgrade
- Support
---
Explicit named imports are prefixed by Http to ease
IDE experience. Message is optional and default to the default message. Additional
parameters are supported.
`typescript
import { HttpNotFound, HttpBadRequest } from "@httpx/exception";
const e = new HttpNotFound();
// π e.message -> 'Not found' (default message)
// π e.statusCode -> 404
// π -> e instanceof HttpNotFound (and HttpClientException, HttpException and Error)
const e400 = new HttpBadRequest("Problems parsing JSON");
// π e.message -> 'Problems parsing JSON'
// ...
`
The createHttpException function allows to create an exception from an
arbitrary status code.
`typescript
import { createHttpException } from "@httpx/exception";
const e404 = createHttpException(404); // e404 instanceof HttpClientException
const e500 = createHttpException(500); // e500 instanceof HttpServerException
`
Additional parameters can be provided as a second argument.
`typescript
import { createHttpException, HttpNotImplemented } from "@httpx/exception";
throw createHttpException(404, "The graal is yet to find !");
const e500 = createHttpException(500, {
message: "Something really wrong happened.",
url: "https://api.dev/gateway",
cause: new HttpNotImplemented(), // or any Error...
});
`
Http exceptions and createHttpException accept a parameter of type string | HttpExceptionParams. If no parameter
is provided the default message is used.
It's possible to attach informational context to an exception. This is particularly useful when used with
centralized logging / error reporting.
| HttpExceptionParams | Type | Description |
| ------------------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| statusCode | number | Http error status code (400-599). |string
| message | | Default or provided message. |string?
| url | | Origin url.. |HttpMethod?
| method | | Origin http method. |string?
| code | | Custom error code (not to be confused with statusCode). |string?
| errorId | | Unique custom error id. |string?
| stack | | @see Error.prototype.stack on MDN. |Error?
| cause | | @see about error cause |HttpValidationIssues[]?
| issues | | Only supported by HttpUnprocessableEntity (422) |
Example:
`typescript
import { HttpGatewayTimeout, HttpInternalServerError } from "@httpx/exception";
const e500 = new HttpInternalServerError({
url: "https://api.dev/gateway",
method: "GET",
code: "ERR_UNREACHABLE_SERVICE",
errorId: nanoid(),
// π nesting
cause: new HttpGatewayTimeout({
message: "This Serverless Function has timed out",
errorId: "cdg1::h99k2-1664884491087-b41a2832f559",
}),
});
`
All parameters are exposed as properties.
| HttpException | Type | Description |
| ------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| statusCode | number | Http error status code (400-599). |string
| message | | Default or provided message. |string?
| url | | Origin url.. |HttpMethod?
| method | | Origin http method. |string?
| code | | Custom error code (not to be confused with statusCode). |string?
| errorId | | Unique custom error id. |string?
| stack | | @see Error.prototype.stack on MDN. |Error?
| cause | | @see about nested errors |ValidationIssues[]?
| issues | | Only supported by HttpUnprocessableEntity (422) |
`typescript
import { HttpUnprocessableEntity } from "@httpx/exception";
const e422 = new HttpUnprocessableEntity({
message: "Request validation failed",
url: "https://acme.org/api/user/create",
method: "POST",
issues: [
// typed as ValidationIssues[]
{
message: "Invalid address",
path: ["addresses", 0, "line1"],
code: "empty_string",
},
],
});
// π e422.issues
// π e422.method === 'POST'
// ...
`
When creating a http exception, it's possible to attach the original error
to the native Error.cause
property.
`typescript`
const e = new HttpBadRequest({
// π nesting
cause: new TypeError({
message: "Param validation failed",
// π nesting: multiple levels are supported
cause: new NoSuchUser("User id is invalid"),
}),
});
> Error cause is supported by >93% of browsers as
> of 12/2023. NodeJs supports it since 16.17. Nested cause will simply be discarded if not supported (no runtime error).
> The error-cause-polyfill can be installed if not provided
> already by your framework.
All exceptions have a static STATUS readonly property.
`typescript
import { createHttpException, HttpMethodNotAllowed } from "@httpx/exception";
const { statusCode } = createHttpException(405);
switch (statusCode) {
case HttpMethodNotAllowed.STATUS:
console.log(statusCode); // π 405
break;
}
`
Http exceptions extends the native Error class
through HttpException and either HttpServerException and HttpClientException.
`typescript
import { createHttpException } from "@httpx/exception";
const e404 = createHttpException(404);
// π e instanceof Error === true
// π e instanceof HttpException === true
// π e instanceof HttpClientException === true
// π e instanceof HttpNotFound === true
// π e instanceof HttpServerException === false
`
`mermaid`
classDiagram
Error <|-- HttpException
Error: +string message
Error: +string? stack
Error: +unknown cause
HttpException : +int statusCode
HttpException : +String url
HttpException : +Error? cause
HttpException <|-- HttpClientException
HttpException <|-- HttpServerException
HttpClientException <|-- HttpNotFound
HttpServerException <|-- HttpInternalServerError
HttpNotFound : 404 statusCode
HttpInternalServerError: 500 statusCode
While the usage of instanceof is preferred, the isHttpException, isHttpClientException andisServerException can be used in place. They will check for instance and willstatusCode
also ensure that the associated is actually valid.
`typescript
import {
isHttpException,
isHttpClientException,
isHttpServerException,
} from "@httpx/exception";
// True
isHttpException(new HttpNotFound());
isHttpClientException(new HttpNotFound());
isHttpServerException(new HttpInternalServerError());
// False
isHttpClientException(new HttpInternalServerError());
isHttpServerException(new HttpNotFound());
isHttpException(new Error());
isHttpServerException(
new (class extends HttpServerException {
constructor() {
super(400); // 400 isn't a server exception
}
})()
);
`
`typescript
import { isHttpErrorStatusCode } from "@httpx/exception";
// True
isHttpErrorStatusCode(404);
// False
isHttpErrorStatusCode(200);
`
Exceptions can be (de-)serialized to json or other formats. Use cases varies from
ssr-frameworks (ie: nextjs getServerSideProps)
/ loggers (sentry, winston...).
Nested error causes are supported but ignored if not supported by
the runtime.
Additionally, you can pass any native errors (Error, EvalError, RangeError, ReferenceError,SyntaxError, TypeError, URIError) as well as a custom one (the later will be transformed to the base type Error).
β οΈ Since v3.0.0:
For security reasons stack traces
won't be serialized anymore by default as they might contain sensitive information in production. To opt-in selectively
for stack traces serialization (ie: development or logging)
convertToSerializable, createFromSerializable, toJson and fromJson functionsSerializerParams.includeStack
accepts a param as second argument.
`typescript
import { fromJson, toJson } from "@httpx/exception/serializer";
const e = new HttpForbidden();
const json = toJson(e); // string
const deserialized = fromJson(json);
// e === deserialized
`
> Tip
> See also how to integrate with superjson
Example for stack traces serialization.
`typescript
import { fromJson, toJson } from "@httpx/exception/serializer";
// To include stack traces (not safe in production)
const jsonWithStack = toJson(new HttpException(500), {
includeStack: process.env.NODE_ENV === "development",
});
const eWithStrack = fromJson(json, {
includeStack: process.env.NODE_ENV === "development",
});
`
Same as JSON but before json.parse/stringify. Allows to use a different encoder.
`typescript
import {
convertToSerializable,
createFromSerializable,
} from "@httpx/exception/serializer";
const e = new HttpForbidden({
cause: new Error("Token was revoked"),
});
const serializableObject = convertToSerializable(e);
const deserialized = createFromSerializable(serializableObject);
// e === deserialized
`
Example for stack traces serialization.
`typescript
import {
convertToSerializable,
createFromSerializable,
} from "@httpx/exception/serializer";
const serializableObject = convertToSerializable(e, {
includeStack: process.env.NODE_ENV === "development",
});
const deserialized = createFromSerializable(serializableObject, {
includeStack: process.env.NODE_ENV === "development",
});
`
Messages are inferred from the Http exception class name. They are
compatible with the popular statuses package.
| Status | Class | Message |
| ------ | ------------------------------- | ------------------ |
| 400 | HttpBadRequest | Bad request |
| 401 | HttpUnauthorized | Unauthorized |
| 402 | HttpPaymentRequired | Payment required |
| 403 | HttpForbidden | Forbidden |
| 404 | HttpNotFound | Not found |
| 405 | HttpMethodNotAllowed | Method not allowed |
| 406 | HttpNotAcceptable | Not acceptable |
| 407 | HttpProxyAuthenticationRequired | ... |
| 408 | HttpRequestTimeout | ... |
| 409 | HttpConflict | ... |
| 410 | HttpGone | ... |
| 411 | HttpLengthRequired | ... |
| 412 | HttpPreConditionFailed | ... |
| 413 | HttpPayloadTooLarge | ... |
| 414 | HttpUriTooLong | ... |
| 415 | HttpUnsupportedMediaType | ... |
| 416 | HttpRangeNotSatisfiable | ... |
| 417 | HttpExpectationFailed | ... |
| 418 | HttpImATeapot | ... |
| 421 | HttpMisdirectedRequest | ... |
| 422 | HttpUnprocessableEntity | ... |
| 423 | HttpLocked | ... |
| 424 | HttpFailedDependency | ... |
| 425 | HttpTooEarly | ... |
| 426 | HttpUpgradeRequired | ... |
| 428 | HttpPreconditionFailed | ... |
| 429 | HttpTooManyRequests | ... |
| 431 | HttpRequestHeaderFieldsTooLarge | ... |
| 451 | HttpUnavailableForLegalReasons | ... |
Server http status error code
| Status | Class | Message |
| ------ | --------------------------------- | --------------------- |
| 500 | HttpInternalServerError | Internal server error |
| 501 | HttpNotImplemented | ... |
| 502 | HttpBadGateway | ... |
| 503 | HttpServiceUnavailable | ... |
| 504 | HttpGatewayTimeout | ... |
| 505 | HttpVersionNotSupported | ... |
| 506 | HttpVariantAlsoNegotiates | ... |
| 507 | HttpInsufficientStorage | ... |
| 508 | HttpLoopDetected | ... |
| 510 | HttpNotExtended | ... |
| 511 | HttpNetwordAuthenticationRequired | ... |
While their usage is not recommended, some status codes might be found in the wild (generally server status codes).
`typescript
import { createHttpException, HttpServerException } from "@httpx/exception";
const nonOfficialStatusCodes = [
[509, "Might refer to bandwidth limit"],
[525, "Might refer to SSL Handshake Failed (ie: cloudflare)"],
[526, "Might refer to Invalid SSL Certificate (ie: cloudflare)"],
["...", "..."],
];
const e = createHttpException(509, {
message: "Bandwidth limit exceeded",
// ... others properties
});
// e instanceof HttpServerException
// alternatively
const alternate = new HttpServerException({
statusCode: 509,
message: "Bandwidth limit exceeded",
// ... others properties
});
`
This typeguard is based on a convention and might help to convert a native error to a specific HttpException.
`typescript
import {
isErrorWithErrorStatusCode,
createHttpException,
type isErrorWithErrorStatusCode,
} from "@httpx/exception";
try {
throw new (class extends Error {
statusCode = 400; // <- by convention
})();
} catch (e) {
// will check if the value is an Error and that there's a statusCode is >=400 && <600
if (isErrorWithErrorStatusCode(e)) {
throw createHttpException(e.statusCode, e.message);
}
}
`
This typeguard is based on a convention and might help to convert an object to a specific HttpException.
`typescript
import {
isObjectWithErrorStatusCode,
createHttpException,
type ObjectWithErrorStatusCode,
} from "@httpx/exception";
const noSuchUser = {
statusCode: 404,
} satisfies ObjectWithErrorStatusCode;
class NoSuchItem extends DomainError implements ObjectWithErrorStatusCode {
statusCode = 404;
}
if (isObjectWithErrorStatusCode(noSuchUser)) {
throw createHttpException(e.statusCode, "Nothing");
}
`
| Level | CI | Description |
|--------------| --- |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Node | β
| CI for 20.x, 22.x, 24.x & 25.x. |
| Browser | β
| Tested with latest chrome (vitest/playwright) |
| Browserslist | β
| > 95% on 01/2025. defaults, chrome >= 96, firefox >= 105, edge >= 113, safari >= 15, ios >= 15, opera >= 103, not dead |
| Bun | β
| Tested with latest (at time of writing >= 1.3.3) |
| Edge | β
| Ensured on CI with @vercel/edge-runtime. |
| Cloudflare | β
| Ensured with @cloudflare/vitest-pool-workers (see wrangler.toml |
| Typescript | β
| TS 4.7+ / are-the-type-wrong checks on CI. |
| ES2022 | β
| Dist files checked with es-check |
> For _older_ browsers:
>
> - π Most frontend frameworks can transpile the library (ie: nextjs...)
> - π You might want to add the error-cause-polyfill to support
> nested errors (if not present they are simply discarded - no runtime errors).
Code and bundler have been tuned to target a minimal compressed footprint
for the browser. In ESM, typical usage the bundle size will vary between 500b to 1300b compressed
(including default messages for the 43 status codes).
ESM individual imports are tracked by a
size-limit configuration.
| Scenario | Size (compressed) |
| -------------------------------------------------- | ----------------: |
| Import generic exception (HttpClientException) | ~ 390b |createHttpException
| Import 1 client exception | ~ 425b |
| Import 2 client exceptions | ~ 447b |
| Import 6 client exceptions | ~ 515b |
| Import (all 43 exceptions) | ~ 1240b |fromJson` (incl all + createHttpException) | ~ 1740b |
| Import
| All serializer functions + exceptions + typeguards | ~ 1950b |
> For CJS usage (not recommended) track the size on bundlephobia.
This library offers a dual cjs/esm bundle. The (optional) serializer code has been tuned to
avoid issues with dual package hazards.
The export fields and the builds are checked on the CI with are-the-types-wrong.
> PS: Plans to remove cjs support might land in a next major version.
This library targets typescript 5+ with descriptions (see
the generated api docs).
> Refer to the UPGRADE.md for detailed information.
| Version | Comment |
| ------- | ------------------------------------------------------------------- |
| 3.x | Serializer functions don't include stack by default |
| 2.x | Node 18.x, modern browsers (see how to transpile) |
Open an issue on github.
Contributions are warmly appreciated. Have a look to the CONTRIBUTING document.
If my OSS work brightens your day, let's take it to new heights together!
Sponsor>), coffee>),
or star β any gesture of support fuels my passion to improve. Thanks for being awesome! πβ€οΈ
![]() | |
JetBrains | Embie.be |
MIT Β© belgattitude and contributors.