QA
Beginner LevelExpress JS

How does Express error-handling middleware work and why does it require 4 arguments?

❓ Interview Prompt: Explain Express error handling, the mandatory (err, req, res, next) 4-argument signature, and catching synchronous vs asynchronous errors.

Express distinguishes normal middleware from Error-Handling Middleware exclusively by the number of arguments in the callback function signature.

The Mandatory 4-Argument Signature:

Error handling middleware must accept exactly 4 arguments: '(err, req, res, next)'.

•
Even if you never use the 'next' parameter in your error handler, you must declare it in the function signature! If you declare only '(err, req, res)', Express treats it as a standard routing middleware, skipping it when an error occurs!

Triggering Error Handlers:

1
Synchronous Errors: Exceptions thrown inside route handlers ('throw new Error("fail")') are caught automatically.
2
Asynchronous Errors: In Express 4, you must pass asynchronous errors to 'next(err)'. In Express 5+, rejected Promises in async handlers are caught automatically!

Code Implementation Example

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

app.get('/api/faulty', (req, res, next) => {
  const err = new Error('Database connection timed out');
  err.status = 503;
  next(err); // Jumps directly to the 4-argument error handling middleware!
});

// ✅ Mandatory 4-argument signature (err, req, res, next)
// Must be placed at the very end of all app.use() and route declarations!
app.use((err, req, res, next) => {
  console.error('[Global Error Handler]', err.stack);
  const statusCode = err.status || 500;
  res.status(statusCode).json({
    success: false,
    error: { message: err.message || 'Internal Server Error', code: statusCode }
  });
});
💡Global 4-argument error handling middleware in Express.
🎯 Interview Key Takeaway

Error handling middleware must declare exactly 4 arguments (err, req, res, next) and be registered after all other routes.

#Error Handling#Middleware#Exceptions#Beginner
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?