🚀 Express.js Intermediate

What is async/await error handling in Express.js?

Answer

Express does not automatically catch errors thrown in async route handlers (in Express 4.x). An uncaught async error crashes the process or causes an unhandled promise rejection. The common solution is a wrapper function: const asyncHandler = fn => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);. Wrap async handlers: app.get('/users', asyncHandler(async (req, res) => { const users = await User.find(); res.json(users); }));. Any thrown error or rejected promise is automatically passed to next(err). Express 5.x (now in stable) handles this automatically — async route handlers are wrapped by default. Alternatively, use express-async-errors package to patch Express 4.