mini-http-errors
v0.1.0
Published
A small but solid http-errors style TypeScript library
Maintainers
Readme
mini-http-errors
A small, TypeScript-based http-errors style HTTP error library.
- HttpError base class:
status,code,details,cause,expose - Convenience classes:
BadRequest,Unauthorized,Forbidden,NotFound,Conflict,UnprocessableEntity,TooManyRequests,InternalServerError - JSON output:
toJSON()returns an API-friendly payload - Type guard:
isHttpError(err) - Factory:
createHttpError(status, message?, options?) - Error cause chain:
new NotFound("x", { cause: err })
Installation
npm install mini-http-errorsBasic Usage
import {
BadRequest,
NotFound,
InternalServerError,
isHttpError,
createHttpError,
} from "mini-http-errors";
function getUser(id: string) {
if (!id) {
throw new BadRequest("id is required", {
details: { field: "id" },
});
}
const user = null; // ...
if (!user) {
throw new NotFound("User not found");
}
return user;
}
try {
getUser("");
} catch (err) {
if (isHttpError(err)) {
console.log(err.toJSON());
} else {
const httpErr = new InternalServerError("Unexpected error", { cause: err });
console.log(httpErr.toJSON({ includeCause: true }));
}
}Express Handler Example
import express from "express";
import {
HttpError,
isHttpError,
InternalServerError,
} from "mini-http-errors";
const app = express();
// ... your routes here
// 404
app.use((_req, _res, next) => {
next(new HttpError(404, "Not Found"));
});
// Global error handler
app.use(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
(err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
let httpError: HttpError;
if (isHttpError(err)) {
httpError = err;
} else {
httpError = new InternalServerError("Unexpected error", { cause: err });
}
const json = httpError.toJSON({
exposeStack: process.env.NODE_ENV !== "production",
includeCause: process.env.NODE_ENV !== "production",
});
res.status(json.error.status).json(json);
}
);Custom Framework Handler
The idea is the same: detect HttpError, otherwise wrap with InternalServerError and return toJSON().
import { isHttpError, InternalServerError } from "mini-http-errors";
export function toHttpResponse(err: unknown) {
const httpErr = isHttpError(err)
? err
: new InternalServerError("Unexpected error", { cause: err });
const json = httpErr.toJSON({
exposeStack: process.env.NODE_ENV !== "production",
includeCause: process.env.NODE_ENV !== "production",
});
return {
status: json.error.status,
body: json,
};
}