express-error-tools
v1.0.0
Published
A lightweight, unopinionated, and highly effective global error-handling utility for Express.js applications.
Maintainers
Readme
express-error-tools
A lightweight, unopinionated, and highly effective global error-handling utility for Express.js applications.
Say goodbye to repetitive try/catch blocks in your route handlers! express-error-tools standardizes your API error responses, automatically handles asynchronous rejections, and provides a clean, seamless developer experience.
📖 Table of Contents
✨ Features
- 🚀 Zero Boilerplate: Auto-patch Express routes to eliminate
try/catchcompletely. - 🛠 Custom Error Class: Standardized
Errorclass to handle operational errors with appropriate HTTP status codes. - 📦 Seamless Responses: Return the
Responsehelper directly from your routes to send formatted JSON instantly. - 🛡 Production Ready: Hides sensitive stack traces in production environments while keeping them detailed in development.
- ʦ TypeScript Native: Built with TypeScript, providing excellent out-of-the-box type definitions and IDE autocomplete.
📦 Installation
Install the package via npm:
npm install express-error-tools🚀 Quick Start
The fastest and cleanest way to use express-error-tools is to patch Express globally. This allows you to write raw async/await routes without any wrappers or try/catch blocks.
import express from 'express';
import { patchExpress, createErrorHandler, Error, Response } from 'express-error-tools';
// 1. Patch Express (must be called before defining routes)
patchExpress();
const app = express();
// 2. Write clean, flat asynchronous routes
app.get('/users/:id', async (req, res) => {
const user = await database.findById(req.params.id);
if (!user) {
// Throws a beautifully formatted 404 error
throw new Error('User not found', 404);
}
// Instantly sends a 200 OK JSON response
return Response("Successfully retrieved user", { user });
});
// 3. Mount the global error handler at the VERY END
app.use(createErrorHandler({
defaultErrorMessage: "Internal server error",
defaultStatusCode: 500,
log: "dev"
}));
app.listen(3000, () => console.log('Server running on port 3000'));🧠 Core Concepts
1. Auto-Patching Express (Recommended)
Instead of wrapping every single route with a wrapper function, patchExpress() modifies Express internally to automatically catch errors for all routes.
import { patchExpress } from 'express-error-tools';
patchExpress(); // Call once at the root of your application2. Seamless Success Responses
Inside any automatically patched route (or manually wrapped route), you can send successful JSON responses by simply returning the Response helper.
import { Response } from 'express-error-tools';
app.post('/users', async (req, res) => {
const user = await database.create(req.body);
// Triggers res.status(201).json(...) automatically
return Response("User created", { user }, 201);
});3. Manual Async Wrapping
If you prefer not to patch Express globally, you can manually wrap your asynchronous route handlers with catchAsync.
import { catchAsync } from 'express-error-tools';
app.post('/users', catchAsync(async (req, res, next) => {
const user = await database.createUser(req.body);
return Response("User created", { user }, 201);
}));4. Throwing Operational Errors
Whenever you encounter an expected failure (e.g., validation failure, resource not found), throw an Error imported from the package. The global error handler will intercept it and format the response correctly.
import { Error } from 'express-error-tools';
if (invalidInput) {
throw new Error('Validation failed', 400);
}⚙️ Configuration
The createErrorHandler middleware must be mounted last in your Express application. It accepts a configuration object to customize its behavior:
app.use(createErrorHandler({
defaultErrorMessage: "Internal server error", // Message sent when a non-operational error crashes the app
defaultStatusCode: 500, // Status code for unknown errors
log: "dev" // Logging level: "dev" | "prod" | "none"
}));📡 Response Formats
express-error-tools ensures all your API errors follow a predictable, standardized JSON structure.
Development Mode (NODE_ENV=development)
Provides detailed stack traces and raw error objects to help you debug quickly:
{
"status": "error",
"message": "Validation failed",
"error": { ... },
"stack": "Error: Validation failed\n at /app/controllers/userController.js:14:11..."
}Production Mode (NODE_ENV=production)
Automatically strips stack traces and prevents sensitive infrastructure details from leaking to the client:
{
"status": "error",
"message": "Validation failed"
}(Note: If a non-operational programming error occurs, it is safely masked with your configured defaultErrorMessage).
📄 License
This project is licensed under the ISC License.
