How do I define and use custom error handling middleware in Express.js?

Question

Grade: Education Subject: Support
How do I define and use custom error handling middleware in Express.js?
Asked by:
71 Viewed 71 Answers

Answer (71)

Best Answer
(408)
Define middleware with four arguments (`err`, `req`, `res`, `next`). Place it *after* all other route handlers and middleware. Inside the middleware, check if `err` exists. If so, format an error response (e.g., JSON with a status code and error message) and send it to the client using `res.status(err.status || 500).json(err.message);`. If no error, call `next()` to pass control to the next middleware.