Node.js
Error middleware
Learn to write Express error middleware.
Error middleware
In Express, error middleware catches errors thrown from routes or passed with next(err). Unlike normal middleware it takes four arguments: (err, req, res, next).
Express sees the four arguments and knows it is an error handler. For example, app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); }). This middleware is placed last, because errors from routes fall through to it. You access the error object with err, set the server error code with res.status(500), and return the error message to the client with .json(). This way the API gives controlled error responses.
Defining error middleware
When defining error middleware, writing four arguments is mandatory. If you write three, Express treats it as a normal middleware and errors never reach it. The first argument must always be err.
For example, app.use((err, req, res, next) => { ... }). When an error occurs, Express calls this middleware and passes the error object as err. The next parameter must be written even if unused, because Express looks at the argument count. If you want to pass the error to the next handler, you can call next(err). Otherwise you finish the response with res.status() and res.json(). This is the standard for error handling in production APIs.
Exercise Add an error middleware
Define an error middleware. Make it a four-argument function (err, req, res, next). Send the response with res.status(500).json({ error: err.message }). The middleware must come AFTER the route. The self-request is ready.
Show example solution
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message });
});
Test yourself
-
How many arguments does an Express error middleware take?
(err, req, res, next)
Show answer
4 — Error middleware takes 4 arguments: err, req, res, next.
-
Complete the error middleware signature
app.use((____, req, res, next) => { res.status(500).json({ error: err.message }); });
Show answer
app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); });
-
Match each argument to its role
- err
- Error object
- req
- Request
- res
- Response
- next
- Next step
Next lesson: Unhandled rejection