Skip to content

mrcaidev/http-errors

Repository files navigation

@mrcaidev/http-errors

Utility classes for HTTP errors.

📦 Installation

npm add @mrcaidev/http-errors # using npm
yarn add @mrcaidev/http-errors # using yarn
pnpm add @mrcaidev/http-errors # using pnpm

🚀 Usage

Simplest:

import { BadRequestError } from "@mrcaidev/http-errors";

throw new BadRequestError(); // status: 400, message: "Bad Request"

Custom error message:

import { BadRequestError } from "@mrcaidev/http-errors";

throw new BadRequestError("Malformed data"); // status: 400, message: "Malformed data"

Dynamic status code:

import { HttpError } from "@mrcaidev/http-errors";

throw new HttpError(400); // status: 400, message: "Bad Request"

Dynamic status code and custom error message:

import { HttpError } from "@mrcaidev/http-errors";

throw new HttpError(400, "Malformed data"); // status: 400, message: "Malformed data"

Dynamic non-standard status code:

import { HttpError } from "@mrcaidev/http-errors";

throw new HttpError(499); // status: 499, message: "Unknown"

Dynamic non-standard status code and custom error message:

import { HttpError } from "@mrcaidev/http-errors";

throw new HttpError(499, "Custom error"); // status: 400, message: "Custom error"

Every error class extends HttpError, which further extends Error.

import { BadRequestError, HttpError } from "@mrcaidev/http-errors";

new BadRequestError() instanceof HttpError; // true
new HttpError(400) instanceof Error; // true

Hover over an error class in the editor to see its definition in RFC.

Editor tooltip

🔎 References

📜 License

MIT