express-global-error
v1.0.1
Published
A simple global error handler for Express with custom errors and async handling
Maintainers
Readme
express-global-error
A simple and lightweight global error handling middleware for Express.js applications.
It helps you standardize error responses, catch async errors, and propagate meaningful messages to clients without repeating boilerplate code.
✨ Features
- Centralized error handling for Express
- Custom
AppErrorclass for structured errors - Middleware
errorHandlerfor formatting and sending errors - Utility
asyncHandlerto wrap async functions - Easy integration with existing Express apps
- Works with TypeScript and JavaScript
📦 Installation
npm install express-global-errorHow to use this package?
// import your package
import { AppError, errorHandler, asyncHandler } from "express-global-error";Create routes with AppError
app.get("/fail", (req, res, next) => {
// throw a custom error
next(new AppError("Resource not found", 404));
});Use asyncHandler for async routes
app.get("/async-fail", asyncHandler(async (req, res, next) => {
throw new AppError("Async operation failed", 500);
}));Register global error handler (last middleware)
app.use(errorHandler);
app.listen(3000, () => {
console.log("Server running on port 3000");
});Example Response
If a route throws new AppError("User not found", 404), the response will be:
{
"status": "error",
"statusCode": 404,
"message": "User not found"
}API Reference
class AppError(message: string, statusCode: number)
Creates a new structured error
message → error message
statusCode → HTTP status code (e.g., 400, 404, 500)
errorHandler(err, req, res, next)
Express middleware to catch and send error responses asyncHandler(fn)
Wraps async route handlers and automatically forwards errors to errorHandler
