Node.js
Error middleware
Learn to write error-handling middleware.
Error middleware
An error middleware takes four parameters: (err, req, res, next). Express treats any four-parameter function as an error handler. Example: app.use((err, req, res, next) => { console.log(err.message); res.status(500).send("Error"); });.
To trigger the error middleware, a route calls next(new Error("message")). Express catches the error and passes it to the four-parameter middleware. Normal middleware (three parameters) does not handle errors; the error middleware is the last registered and four-parameter one. This pattern lets you handle all errors consistently in one place: the route just says next(err), the error middleware shapes the response.
Throwing errors with next(err)
When an error occurs in a route, you call next(err). Express skips the normal middleware chain and jumps directly to the error middleware. Example: app.get("/boom", (req, res, next) => { next(new Error("Crashed")); });.
The error object's message property describes the error. In the error middleware you access it via err.message. This pattern handles errors centrally instead of writing try/catch inside each route. You can also define multiple error middlewares; they chain with next(err). This lets you route different error types to different handlers.
Exercise Add error middleware
Add the route app.get("/boom", (req, res, next) => { next(new Error("Crashed")); }). Add error middleware app.use((err, req, res, next) => { console.log("Error: " + err.message); res.status(500).send("Server error"); }). The server closes itself.
Show example solution
const express = require("express");
const app = express();
app.get("/boom", (req, res, next) => {
next(new Error("Crashed"));
});
app.use((err, req, res, next) => {
console.log("Error: " + err.message);
res.status(500).send("Server error");
});
const server = app.listen(3000, () => {
const http = require("http");
http.get("http://localhost:3000/boom", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});
Test yourself
-
How many parameters does error middleware take?
app.use((err, req, res, next) => { ... })
Show answer
Four — Four parameters: err, req, res, next.
-
Match each piece to its role
- next(new Error())
- Throws an error
- err.message
- Error description
- (err, req, res, next)
- Error middleware signature
- res.status(500)
- Sends error status
-
Complete the error middleware signature
app.use((err, req, res, ____) => { console.log(err.message); res.status(500).send("Hata"); });
Show answer
app.use((err, req, res, next) => { console.log(err.message); res.status(500).send("Hata"); });
Next lesson: Body parser