Express error-handling middleware signature
recognizing the four-argument signature.
(err, req, res, next) with err first, identified by arity, placed last after all routes.
omitting the err parameter or registering it before the routes it should catch.
WHAT THIS TESTS This checks that you know how Express distinguishes error-handling middleware from regular middleware and the placement rule that makes it work.
A GOOD ANSWER COVERS Error-handling middleware has the signature (err, req, res, next) with four parameters, and the err parameter comes first. Express identifies error handlers purely by function arity: it counts four declared arguments and routes errors there. This is why you must declare all four even if you do not use next. Errors reach this handler when any middleware or route calls next(err) with a non-null argument, or when a synchronous error is thrown in a handler. Placement is critical: error handlers must be registered last, after all routes and other middleware, because Express walks the stack in order and only falls through to error handlers once an error is in flight.
COMMON WRONG ANSWERS Writing (req, res, next) and wondering why errors are not caught; with three args Express treats it as ordinary middleware. Omitting the unused next and triggering arity issues. Registering the error handler before routes, so the stack never reaches it. Assuming a try/catch in one route covers the whole app.
LIKELY FOLLOW-UPS What happens if you have multiple error handlers? How do you forward to the default Express error handler? How do async errors reach this middleware?
ONE CONCRETE EXAMPLE app.use((err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ error: err.message }); }); Registered after all routes, this catches anything passed via next(err). A route doing next(new Error('boom')) lands here and returns a 500 JSON body, while a normal three-argument function in the same spot would silently be skipped during error propagation.
Read the original → expressjs.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.