Skip to main content

Command Palette

Search for a command to run...

Understanding asyncHandler in Express.js (with Higher Order Functions)

Published
2 min read

❓ The Problem with Async Route Handlers

  • Express catch synchronous error automatically, but it doesn’t catch error thrown inside async functions.
router.post("/login", async (req, res) => {
  const user = await User.findOne({ email: req.body.email });
  if (!user) {
    throw new Error("User not found");
  }
});

the error is not reach Express.js error middleware ( ERROR :: calling database )

To fix this, Developer often user try…catch block everywhere.

Repetitive Error Handling ❌

router.post("/login", async (req, res, next) => {
  try {
    // logic
  } catch (err) {
    next(err);
  }
});
  • Code becomes repetitive

  • Business logic and error handling get mixed

  • Readability suffers

✅ The Solution: asyncHandler

asyncHandler is a utility function that wrap async route handlers and forward error to Express automatically.

Implementation of asyncHandler by Promise

function asyncHandler(fn) {
    return (req, res, next) => {
        Promise.resolve(fn(req, res, next)).catch((err) => next(err))
    };
}

Route Definition 🛣️

router.route('/register').post(asyncHandler(Login));

Implementation of asyncHandler by try….catch

function asyncHandler(fn) {
    return async(req, res, next) => {
       try {
        await fn(req, res, next);
       } catch (err) {
        next(err);
       }
    };
}

🎯 Benefits of Using asyncHandler

  • Eliminates repetitive try...catch

  • Cleaner route handlers

  • Centralized error handling

  • Follows functional programming principles

  • Easy to reuse

Final Thoughts

asyncHandler is a small utility with a big impact.
It demonstrates how Higher Order Functions can simplify complex problems like asynchronous error handling in Express.js.