QA
Intermediate LevelExpress JS

How do you write a clean higher-order async wrapper function in Express 4?

❓ Interview Prompt: Explain avoiding repetitive try/catch blocks in Express 4 async controllers using higher-order wrapper functions.

In Express 4, unhandled Promise rejections inside 'async' controllers crash the process unless caught and passed to 'next(err)'. Writing 'try/catch' in every controller introduces boilerplate code.

Higher-Order Async Wrapper:

Wrap async controllers in a helper function:

'const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);'.

Automatically catches any thrown errors or Promise rejections and forwards them to the global error middleware!

Code Implementation Example

javascript
import express from 'express';
const app = express();

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

// Controllers write clean code without try/catch boilerplate!
app.get('/api/users/:id', asyncHandler(async (req, res) => {
  const user = await db.findUser(req.params.id);
  if (!user) throw new Error('User not found'); // Caught automatically!
  res.json(user);
}));
💡Higher-order asyncHandler wrapper forwarding Promise rejections to error middleware.
🎯 Interview Key Takeaway

Use an asyncHandler wrapper in Express 4 to forward rejected Promises to error middleware without try/catch boilerplate.

#asyncHandler#Async#Error Handling#Intermediate
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?