View as Json

Async Handler

The Async Handler component is a foundational Express utility that ensures all errors thrown inside asynchronous route handlers are reliably captured and forwarded to Express’s global error middleware.


Installation Guide

Install the component using the servercn CLI:

npx servercn-cli add async-handler

Basic Implementation

src/utils/async-handler.ts
import { Request, Response, NextFunction } from "express";
 
export type AsyncRouteHandler = (
  req: Request,
  res: Response,
  next: NextFunction
) => Promise<unknown>;
 
export function AsyncHandler(fn: AsyncRouteHandler) {
  return function (req: Request, res: Response, next: NextFunction) {
    Promise.resolve(fn(req, res, next)).catch(next);
  };
}

Usage Example

import { Request, Response, NextFunction } from "express";
import { AsyncHandler } from "..utils/async-handler";
 
export const registerUser = AsyncHandler(
  async (req: Request, res: Response, next: NextFunction) => {
    /*
     * business logic
     * your actual code
     */
  }
);

File & Folder Structure

Loading files...

Installation

npx servercn-cli add async-handler