Centralized error-handling middleware
Express error flow.
error middleware takes four args err, req, res, next, is defined last, and runs when next(err) is called or sync errors throw.
omitting the err parameter so Express treats it as normal middleware.
WHAT THIS TESTS This assesses understanding of Express's error pipeline and how to consolidate error responses instead of duplicating try/catch handling in every route.
A GOOD ANSWER COVERS Error-handling middleware is distinguished solely by having four parameters: err, req, res, and next. Express inspects a middleware function's arity, and a four-argument function is treated as an error handler rather than a normal one. Errors reach it in two ways: when any handler calls next(err) with an argument, or when a synchronous route handler throws, which Express catches automatically. Note that for asynchronous errors in older Express you must pass them to next yourself, since Express 4 does not auto-catch rejected promises. You implement a centralized catch-all by defining one error handler after all your routes and other middleware. Inside it you log the error, optionally inspect a status property to choose a code, and send a single consistent response, for example a JSON error body with an appropriate status, avoiding leaking stack traces to clients in production.
COMMON WRONG ANSWERS Defining the handler with three parameters, so Express never invokes it for errors. Placing it before the routes, so errors thrown later never reach it. Assuming async rejections are caught automatically in Express 4 without next(err). Sending raw stack traces to the client.
LIKELY FOLLOW-UPS How do you forward async errors to the handler. How does Express 5 change async error handling. How would you attach a status code to a custom error.
ONE CONCRETE EXAMPLE After all routes you add app.use((err, req, res, next) => { console.error(err); res.status(err.status || 500).json({ error: err.message }); });. A route doing next(new Error('boom')) or throwing synchronously lands here, producing a uniform 500 JSON response and one place to log every failure.
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.