@anhkhoakz/express-http-errors
v1.0.0
Published
Express-friendly HTTP errors with typed status factories.
Readme
@anhkhoakz/http-errors
Express-friendly HTTP errors with typed status factories.
The package exports a single HttpError class with:
err.statusanderr.statusCodefor Express middleware- generated helpers like
HttpError.notFound()andHttpError[404]() - a
HttpError.success()alias for200 OK - optional
details,headers,cause, andexposemetadata - zero runtime dependencies
Install
npm install @anhkhoakz/http-errorsQuick Start
import express from "express";
import { HttpError } from "@anhkhoakz/http-errors";
const app = express();
app.get("/users/:id", async (req, res) => {
if (req.params.id === "0") {
throw HttpError.notFound("User not found", {
details: { userId: req.params.id },
});
}
res.json({ id: req.params.id });
});
app.use((err, req, res, next) => {
if (!HttpError.is(err)) {
return next(err);
}
if (err.headers) {
res.set(err.headers);
}
res.status(err.status).json({
error: err.message,
details: err.expose ? err.details : undefined,
});
});Express 5 treats rejected async handlers as errors automatically. Error
middleware must still be registered last and use the four-argument signature
(err, req, res, next).
API
HttpError
import { HttpError } from "@anhkhoakz/http-errors";
throw HttpError.badRequest("Invalid payload");
throw HttpError[401]("Missing token");
throw HttpError.success();Each instance includes:
type HttpErrorInstance = {
message: string;
status: number;
statusCode: number;
statusText: string;
expose: boolean;
headers?: Readonly<Record<string, string | readonly string[]>>;
details?: unknown;
cause?: unknown;
};HttpError.from(status, ...)
Create an error when the status is only known at runtime.
const status = 429 as const;
const error = HttpError.from(status, "Rate limit exceeded");HttpError.is(value)
Runtime guard for custom middleware.
if (HttpError.is(err)) {
console.log(err.status, err.message);
}HttpError.isStatusCode(value)
Check whether a number is a generated status code.
if (HttpError.isStatusCode(input)) {
throw HttpError.from(input);
}HttpError.getStatus(code)
Read generated metadata for a status code.
const status = HttpError.getStatus(404);
status.name;
status.constant;
status.comment.description;
status.comment.doc;Types
import type {
HttpErrorHeaders,
HttpErrorOptions,
HttpErrorStatusCode,
HttpErrorStatusConstant,
HttpErrorStatusName,
} from "@anhkhoakz/http-errors";Development
bun install
bun run generate
bun run typecheck
bun test
bun run build