forgerror
v1.0.2
Published
Zero-config error handler for Node.js. Automatically detects and handles errors from MongoDB, MySQL, PostgreSQL and SQLite with a single function.
Downloads
462
Maintainers
Readme
forgerror
Zero-config error handler for Node.js. Automatically detects and handles errors from MongoDB, MySQL, PostgreSQL and SQLite with a single function.
Install
npm install forgerrorSetup
import { handleError } from "forgerror";
app.use((err, req, res, next) => {
handleError(err, res);
});Dev Mode
In development you can enable full error details:
app.use((err, req, res, next) => {
handleError(err, res, { dev: true });
});Production response:
{
"success": false,
"message": "Email already exists"
}Dev mode response:
{
"success": false,
"message": "Email already exists",
"error": "MongoServerError: E11000 duplicate key...",
"stack": "at handler.js:25..."
}What it handles
| Type | Examples | | ------------- | ---------------------------------------------- | | MongoDB | Duplicate key, validation, cast error, timeout | | MySQL | Duplicate entry, table not found, deadlock | | PostgreSQL | Unique violation, foreign key, not null | | SQLite | Constraint, busy, locked, corrupt | | JWT | Invalid token, expired token | | App errors | Your own thrown errors | | Server errors | Unknown or unexpected errors |
Response format
Every error returns the same clean response:
{
"success": false,
"message": "Email already exists"
}Throwing your own errors
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.isOperational = true;
}
}
throw new AppError("User not found", 404);
app.use((err, req, res, next) => {
handleError(err, res);
});Full example
import express from "express";
import { handleError } from "forgerror";
const app = express();
app.post("/register", async (req, res, next) => {
try {
await User.create(req.body);
res.status(201).json({ success: true });
} catch (err) {
next(err);
}
});
app.use((err, req, res, next) => {
handleError(err, res);
});License
MIT
