Sequence NODE_245
Medium

Create Async Wrapper for Express Route Handlers

Express.js
Node.js
Technical Specification

Create a helper function wrapAsync that wraps async route handlers and forwards errors to next.

Input/Output Samples
Input:app.get('/users', wrapAsync(async..))
Output:Errors go to error handler
Optimal Logic Path
function wrapAsync(fn) {
  return function (req, res, next) {
    Promise.resolve(fn(req, res, next)).catch(next);
  };
}

module.exports = { wrapAsync };
Architectural Deep-Dive
We avoid repeating try/catch in every async route by centralizing async error forwarding.