Async Error Handler Wrapper
Higher-order function that wraps async Express route handlers and forwards rejected promises to error middleware.
import { Request, Response, NextFunction, RequestHandler } from 'express';
type AsyncHandler = (
req: Request,
res: Response,
next: NextFunction
) => Promise<void>;
export const asyncHandler = (fn: AsyncHandler): RequestHandler => {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
};
// Usage:
// app.get('/users/:id', asyncHandler(async (req, res) => {
// const user = await db.users.findById(req.params.id);
// if (!user) throw new NotFoundError('User not found');
// res.json(user);
// }));Use Cases
- Express route error handling
- Avoiding try-catch boilerplate
- Centralized error management
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
JWT Verify Middleware
Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.
In-Memory Rate Limiter for Express
Token bucket rate limiter middleware for Express with configurable window and max requests per IP.
Express Zod Request Validation
Validate Express request body, params, and query with Zod schemas via reusable middleware.
File Upload with Multer
Configure Multer for disk storage with file type validation, size limits, and unique filenames for Express.