1.0.3 โข Published 5 months ago
express-universal-error-handler v1.0.3
express-universal-error-handler ๐ก๏ธ
A universal error handler middleware for Express.js that handles synchronous, asynchronous, and custom errors gracefully.
๐ฆ Installation
npm install express-universal-error-handler
๐ Usage
const express = require('express');
const { errorHandler, CustomError } = require('express-universal-error-handler');
const asyncWrapper = require('express-universal-error-handler/asyncWrapper');
const app = express();
// Example Sync Route
app.get('/sync-error', () => {
throw new Error('Sync Error Example');
});
// Example Async Route
app.get('/async-error', asyncWrapper(async () => {
throw new Error('Async Error Example');
}));
// Example Custom Error Route
app.get('/custom-error', () => {
throw new CustomError('Custom Error Example', 400);
});
// Use the error handler middleware
app.use(errorHandler());
// Start Server
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
โ Features
- ๐ฆ Simple plug-and-play Express middleware
- ๐ช Handles sync, async, and custom errors
- ๐ Structured JSON error responses
- ๐ Lightweight and fast
๐งช Testing
Run tests using Jest:
npm test
๐ก๏ธ API
asyncWrapper(fn)
Wraps async functions to catch errors automatically and pass them to the error handler.
errorHandler(options)
Handles all types of errors and returns consistent JSON responses. โข logErrors (boolean) โ Enable logging (default: true) โข hideStackTrace (boolean) โ Hide error stack traces (default: based on environment)
CustomError(message, statusCode)
Create custom application errors with status codes.
๐ก Examples
Custom Error Example:
app.get('/custom-error', () => {
throw new CustomError('This is a custom error', 400);
});
Async Error Example::
app.get('/async-error', asyncWrapper(async () => {
throw new Error('Async error occurred');
}));
Structured Error Response Example:
{
"status": "error",
"message": "Async error occurred",
"code": 500
}
๐งฐ Requirements
- Express.js 4+
- Node.js 16+