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.
Previous
How do you connect Express.js to MongoDB using Mongoose?
Next
What is the morgan package and how is it used?
More Express.js Questions
View all →- Intermediate How do you implement JWT authentication in Express.js?
- Intermediate What is Express middleware chaining and how does it work?
- Intermediate What is the helmet package and why should you use it?
- Intermediate How do you implement rate limiting in Express.js?
- Intermediate What is input validation and how do you do it in Express?