Error-Handling Middleware

noun

say it: “AIR-er HAND-ling MID-ul-wair” /ˈɛrər ˈhændlɪŋ ˈmɪdəlwɛr/

Express middleware with four parameters (err, req, res, next) that turns any error in a route into one consistent response.

What is Error-Handling Middleware?

Express error-handling middleware has four parameters (err, req, res, next) and turns errors into responses in one place.

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

In a sentence

  • “The error-handling middleware turns every unexpected error into a 500 with the same JSON shape.”
  • “Put the error-handling middleware after every route, or it never sees their errors.”

Level: Journeyman · More Node.js terms at this level

Updated