0
0
ExpressConceptBeginner · 3 min read

Error Handling Middleware in Express: What It Is and How It Works

In Express, error handling middleware is a special function that catches and processes errors during request handling. It has four parameters (err, req, res, next) and helps keep your app stable by managing errors in one place.
⚙️

How It Works

Error handling middleware in Express acts like a safety net for your web app. Imagine you are cooking and accidentally spill something; instead of stopping everything, you clean it up quickly and keep cooking. Similarly, when an error happens in your app, this middleware catches it and decides what to do next.

It works by having a special function with four inputs: the error itself, the request, the response, and a next step function. When an error occurs anywhere in your app, Express passes it to this middleware instead of crashing or hanging. This way, you can send a friendly message to users or log the problem for fixing later.

💻

Example

This example shows a simple Express app with error handling middleware that catches errors and sends a message to the user.

javascript
import express from 'express';
const app = express();

app.get('/', (req, res) => {
  throw new Error('Oops! Something went wrong.');
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.message);
  res.status(500).send('Error caught: ' + err.message);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 When visiting http://localhost:3000, the browser shows: "Error caught: Oops! Something went wrong."
🎯

When to Use

You should use error handling middleware whenever you want to manage unexpected problems in your Express app gracefully. It is especially useful for catching bugs, database errors, or invalid user input without crashing your server.

For example, if a user requests a page that causes a problem, instead of showing a confusing error or a blank page, you can show a friendly message or redirect them. It also helps developers by logging errors in one place, making debugging easier.

Key Points

  • Error handling middleware has four parameters: err, req, res, next.
  • It catches errors from routes or other middleware.
  • It helps keep your app stable and user-friendly.
  • Always place error handling middleware after all other middleware and routes.

Key Takeaways

Error handling middleware in Express catches and manages errors centrally.
It must have four parameters: err, req, res, and next.
Use it to send user-friendly error messages and log problems.
Place it after all routes and other middleware in your app.
It helps keep your server running smoothly even when errors occur.