Error Handling Middleware in Express.js

What is Error-Handling Middleware?

  1. It is a special type of middleware in Express.js.
  2. It catches and handles errors that occur during route processing.
  3. Helps to show a friendly message instead of crashing the server.


Basic Error Handler

app.get("/users", (req, resp) => {
resp.send1("User Page"); // Typo will cause error
});



function errorHandling(error, req, resp, next) {
resp.status(error.status || 500).send("Try after some time");
}
app.use(errorHandling);


Output: Server doesn’t crash, shows:

“Try after some time”


Custom Error with next(error)

app.get("/error", (req, resp, next) => {
const error = new Error("Something went wrong");
error.status = 404;
next(error); // Pass error to middleware
});


app.use((error, req, resp, next) => {
resp.status(error.status || 500).send("Try after some time");
});

Output: Returns status 404 with message

“Try after some time”