make-errors-known
v1.0.1
Published
A lightweight Express error-handling utility for TypeScript apps.
Maintainers
Readme
make-errors-known
A lightweight Express error-handling utility for TypeScript apps.
Overview
This package gives you:
- a custom
AppErrorclass - a reusable
errorHandlermiddleware - a
tryCatchwrapper for async route handlers
Installation
npm install make-errors-known expressAPI
AppError
Use this when you want to create a request or application error with a status code.
import { AppError } from "make-errors-known";
const user = await findUserById(req.params.id);
if (!user) {
throw new AppError("User not found", 404);
}errorHandler
Register this middleware at the end of your Express middleware stack.
import express from "express";
import { errorHandler } from "make-errors-known";
const app = express();
app.use(express.json());
app.use(
errorHandler({
customRules: [
{
match: (err: any) => err.code === "MONGO_DOWN_ERROR",
statusCode: 503,
message: "Database is currently offline. Please try again later.",
},
],
defaultMessage: "An unexpected internal server error occurred.",
}),
);If a rule matches, the middleware responds with the configured status code and message. Otherwise, it falls back to the default response.
tryCatch
tryCatch is meant for async work only. Its job is to catch rejected promises from async route handlers and pass them to Express with next(err).
import { tryCatch, AppError } from "make-errors-known";
app.get(
"/data",
tryCatch(async (req, res, next) => {
const data = await fetchSomeDataFromDatabase();
if (!data) {
throw new AppError("Data missing", 404);
}
res.status(200).json({
status: "success",
data,
});
}),
);This is the intended use case: asynchronous logic that returns a promise.
Why it throws when used synchronously
tryCatch is not designed for synchronous functions. It expects the callback to return a promise and immediately calls .catch() on it.
import { tryCatch } from "make-errors-known";
const badExample = tryCatch((req, res) => {
return "not a promise";
});This throws at runtime because the result is a string, not a promise.
Example error:
TypeError: callback(...).catch is not a functionWhy this happens:
tryCatchcallscallback(req, res, next).catch(...)- a synchronous function returns a plain value instead of a promise
- plain values do not have
.catch()
So if you are doing async work, tryCatch is useful. If you are doing synchronous work, it should not be used.
Example custom rule
const customRules = [
{
match: (err: any) => err.code === "DB_ERROR",
statusCode: 500,
message: "Database is currently unavailable.",
},
];License
ISC
