How does error handling work in Express.js?
Answer
Express has a special error-handling middleware with four parameters: (err, req, res, next). It must be defined with exactly four parameters for Express to recognize it as an error handler. It is placed after all other middleware and routes. To trigger it, call next(err) from any middleware or route handler. Example: app.use((err, req, res, next) => { console.error(err); res.status(500).json({ error: err.message }); });. For async route handlers, errors thrown in async functions must be caught and passed to next(err) — Express does not automatically catch async errors in versions before 5.x. A popular solution is a asyncHandler wrapper that auto-catches and forwards async errors.
Previous
What is the next() function in Express middleware?
Next
What is CORS and how do you enable it in Express?