🎓 A1Learner
🔍
0 of 50 lessons completed

Error Handling in Express

Error handling in Express answers a failed ask with a clear message. A special function with four inputs catches the error.

A route that fails

This route throws an error on each ask.

app.get("/boom", (req, res) => {
  throw new Error("Boom");
});

Ask for the failing route

This command asks the server for the failing route.

curl http://localhost:3000/boom

Example

const express = require("express");

const app = express();

app.get("/boom", (req, res) => {
  throw new Error("Boom");
});

app.use((err, req, res, next) => {
  res.status(500).json({ error: "Something went wrong" });
});

app.listen(3000, () => {
  console.log("Notes API running on http://localhost:3000");
});

Key points

  • Error handling in Express answers a failed ask with a clear message.
  • A route can throw an error when something goes wrong.
  • An error handler is a function with four inputs.
  • The four inputs are error, request, response, and next.
  • Express runs it when a route throws an error.
  • Use res.status(500) to mark the answer as a server error.

In this example, the /boom route throws an error on each ask. The app.use line adds an error handler after the route. The handler answers with status 500 and a short message. A visit to /boom gets that message back.

Note

Put the error handler after the routes, so it catches them.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How many inputs does an Express error handler take?