A simple global error handler for Express with custom errors and async handling
npm install express-global-errorA 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.
---
AppError class for structured errorserrorHandler for formatting and sending errorsasyncHandler to wrap async functions---
bash
npm install express-global-error
`
How to use this package?
`JS
// import your package
import { AppError, errorHandler, asyncHandler } from "express-global-error";
`Create routes with AppError
`JS
app.get("/fail", (req, res, next) => {
// throw a custom error
next(new AppError("Resource not found", 404));
});
`Use asyncHandler for async routes
`JS
app.get("/async-fail", asyncHandler(async (req, res, next) => {
throw new AppError("Async operation failed", 500);
}));
`
Register global error handler (last middleware)
`JS
app.use(errorHandler);app.listen(3000, () => {
console.log("Server running on port 3000");
});
`
Example Response
$3
`JS
{
"status": "error",
"statusCode": 404,
"message": "User not found"
}
``