Node.js
nodejs express error-handling

asyncHandler

Express.js middleware wrapper for handling async route errors automatically.

import { Request, Response, NextFunction } from 'express';

type AsyncFunction = (
  req: Request,
  res: Response,
  next: NextFunction
) => Promise<any>;

export const asyncHandler = (fn: AsyncFunction) => {
  return (req: Request, res: Response, next: NextFunction) => {
    Promise.resolve(fn(req, res, next)).catch(next);
  };
};

Usage

// Without asyncHandler - need try/catch everywhere
app.get('/users/:id', async (req, res, next) => {
  try {
    const user = await User.findById(req.params.id);
    res.json(user);
  } catch (error) {
    next(error);
  }
});

// With asyncHandler - cleaner code
app.get('/users/:id', asyncHandler(async (req, res) => {
  const user = await User.findById(req.params.id);
  if (!user) {
    throw new Error('User not found');
  }
  res.json(user);
}));

Benefits

  • Eliminates repetitive try/catch blocks
  • Automatically forwards errors to Express error handler
  • Keeps route handlers clean and focused