InterviewBuddy
All interview questions

What is the signature of Express error-handling middleware?

Intermediate

Answer

Error middleware uses four arguments: err, req, res, and next. Register it after routes and ordinary middleware.

Explanation

If headers were already sent, delegate with next(err) rather than sending another response.

Example

app.use((err, req, res, next) => { if (res.headersSent) return next(err); res.status(500).json({ error: 'Request failed' }); });