express-async-safe-guard
v1.1.1
Published
A bulletproof, type-safe async handler for Express with native try/catch error wrapping.
Maintainers
Readme
express-async-safe-guard 🛡️
A lightweight, bulletproof async handler wrapper for Express. It completely eliminates server crashes caused by unhandled runtime exceptions while providing deep TypeScript inference for your request pipeline.
Why use this over traditional handlers?
Standard shortcuts like Promise.resolve(fn(...)).catch(next) have a flaw. If a developer makes a synchronous typo or variable mistake at the very top of a controller before an await keyword runs, it can bypass the promise chain entirely.
express-async-safe-guard runs your controllers inside an explicit, native try/catch execution block, capturing both synchronous mistakes and asynchronous database failures, ensuring 100% server uptime.
💾 Installation
npm install express-async-safe-guard
# or
yarn add express-async-safe-guard
# or
pnpm add express-async-safe-guard
## Section 3: Basic Usage (The Quick Start)
Show the simplest way to use it without any complex TypeScript setups. This lets developers drop it into existing JavaScript or TypeScript projects instantly.
## 💻 How to Use
### 1. Basic Setup
Wrap any asynchronous controller logic to automatically pass internal errors down to your global Express error-handling middleware.
import { Router } from 'express';
import { controllerAsyncHandler } from 'express-async-safe-guard';
const router = Router();
router.get('/dashboard', controllerAsyncHandler(async (req, res) => {
// Any error thrown here is automatically routed to next(error)
const data = await fetchDashboardData();
res.json(data);
}));
---
## Section 4: Advanced TypeScript Usage (The Superpower)
This is the most important section for TypeScript developers. Show them how passing types into your package eliminates manual type casting (`as UserType`).
### 2. Advanced Type Inference (Body, Query, & Params)
Pass your custom data interfaces straight into the wrapper generic slots to instantly secure type-safety across your endpoints.
import { controllerAsyncHandler } from 'express-async-safe-guard';
interface UpdateProfileBody {
bio: string;
theme: 'light' | 'dark';
}
interface SearchQuery {
limit?: string;
}
interface RouteParams {
id: string;
}
// Pass interfaces in exact order: <Body, Query, Params>
export const updateProfile = controllerAsyncHandler<UpdateProfileBody, SearchQuery, RouteParams>(
async (req, res) => {
const { id } = req.params; // Automatically typed as string
const { limit } = req.query; // Automatically typed as string | undefined
const { bio, theme } = req.body; // Automatically typed with absolute autocomplete!
res.status(200).json({ success: true });
}
);
---
## Section 5: The Global Setup Reminder
Developers often forget that an async handler wrapper is useless without a global error catch block. Remind them to add this to their core server application file (`app.ts` or `server.ts`).
### 3. Setup the Global Error Middleware
Ensure your central Express application handles the intercepted failures. Place this middleware at the absolute bottom of your main server file:
import express from 'express';
const app = express();
// ... Your router bindings go here ...
// Centralized Safety Net
app.use((err: any, req: any, res: any, next: any) => {
console.error(` [Crash Prevented]: ${err.message}`);
res.status(err.statusCode || 500).json({
success: false,
error: err.message || 'Internal Server Error'
});
});
---
## Section 6: Clean Up with a License
End with a standard license block to make it safe for enterprise or open-source contribution.
## 📄 License
MIT © Gemini Assist