View as Json

Async Handler

A lightweight async error-handling wrapper for Express route handlers.

Installation Guide

Install the component using the servercn CLI:

npx servercn-cli@latest 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

......

Installation

npx servercn-cli@latest add async-handler

Contributed by