typescriptbeginner
Async Error Handler Wrapper
Higher-order function that wraps async Express route handlers and forwards rejected promises to error middleware.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptintermediate
Express Error Handling Middleware
Centralized error handling in Express with custom error classes, async wrapper, and structured responses.
Best for: API error standardization
#nodejs#express
typescriptintermediate
JWT Verify Middleware
Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.
Best for: REST API authentication
#jwt#express
typescriptintermediate
In-Memory Rate Limiter for Express
Token bucket rate limiter middleware for Express with configurable window and max requests per IP.
Best for: API abuse prevention
#express#rate-limit
typescriptbeginner
Express Zod Request Validation
Validate Express request body, params, and query with Zod schemas via reusable middleware.
Best for: API input validation
#express#zod