How does Express's error-handling middleware process errors that include an HTTP status code?

Responsive Ad Header

Question

Grade: Education Subject: Support
How does Express's error-handling middleware process errors that include an HTTP status code?
Asked by:
93 Viewed 93 Answers

Answer (93)

Best Answer
(666)
An Express error-handling middleware function has the signature `(err, req, res, next)`. When an error is passed to `next(err)`, Express skips all subsequent non-error-handling middleware and routes the request to the first error-handling middleware. Inside this middleware, you can check for `err.statusCode` (or `err.status`) and use that value to set the HTTP response status. If `err.statusCode` is not set, a default (often 500 Internal Server Error) can be used. For example: `app.use((err, req, res, next) => { const statusCode = err.statusCode || 500; res.status(statusCode).json({ message: err.message || 'Something went wrong', status: statusCode }); });`.