Error middleware
- Node.js course
- Intermediate
- Lesson 79/116
- 5 min
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.
Practice 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.
Starter code
const express = require("express");
const app = express();
app.get("/", (req, res, next) => {
next(new Error("test"));
});
// Error middleware (4 arguments) — return 500 JSON
// write here
// Self-request (boilerplate)
const server = app.listen(3000, () => {
const http = require("http");
http.get("http://localhost:3000/", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log(body); server.close(); });
});
});Sample solution
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message });
});Expected output
{"error":"test"}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How many arguments does an Express error middleware take?
(err, req, res, next)- 2
- 3
- 4 Correct answer
- 1
Explanation: Error middleware takes 4 arguments: err, req, res, next.
2 Complete the error middleware signature
app.use((____, req, res, next) => { res.status(500).json({ error: err.message }); });
app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); });
Explanation: The first argument is err; Express counts it as an error handler.
3 Match each argument to its role
| Term | Meaning |
|---|---|
err |
Error object |
req |
Request |
res |
Response |
next |
Next step |