# Error-Handling Middleware — Express.js

Source: https://www.geekswithgeeks.com/en/expressjs/ex-error-handling

> A special 4-argument middleware Express recognizes automatically.

## The 4-argument signature

A middleware with exactly `(err, req, res, next)` is treated as an **error handler**. Express skips straight to it whenever `next(err)` is called anywhere.

## A centralized handler

Register it **last**, after all routes — one place to log errors and shape the JSON response.

```javascript
app.get('/risky', (req, res, next) => {
  try {
    throw new Error('Something broke');
  } catch (err) {
    next(err);   // hand off to the error handler
  }
});

// must be registered after all routes
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: err.message || 'Internal Server Error' });
});
```

**Quiz:** How many arguments must an error-handling middleware function accept?

- [ ] 2
- [ ] 3
- [x] 4

*Answer:* 4. Express identifies error handlers purely by arity — exactly (err, req, res, next).
