Source

utils/asyncHandler.js

/**
 * Wraps an async function to catch any rejections and forward them to the next middleware.
 * This allows you to use async/await in route handlers without manually wrapping them in try-catch blocks.
 * @category Utils
 * @template R - Request type (defaults to Express Request)
 * @template S - Response type (defaults to Express Response)
 * @param {Function} fn - The async function to wrap
 * @returns {Function} A function that can be used as an Express route handler
 * @example
 * ```typescript
 * // Instead of:
 * app.get('/users', async (req, res, next) => {
 *   try {
 *     const users = await userService.getUsers();
 *     res.json(users);
 *   } catch (error) {
 *     next(error);
 *   }
 * });
 *
 * // You can do:
 * app.get('/users', asyncHandler(async (req, res) => {
 *   const users = await userService.getUsers();
 *   res.json(users);
 * }));
 * ```
 */
export const asyncHandler = (fn) => (req, res, next) => {
    // Use void to explicitly ignore the promise return value
    // This prevents ESLint warnings about floating promises
    void fn(req, res, next).catch(next);
};