0
0
Expressframework~10 mins

Centralized error handler in Express - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Centralized error handler
Request received
Route handler runs
Error occurs?
NoSend response
Yes
Pass error to next()
Centralized error handler middleware
Send error response
The request goes to a route handler. If an error happens, it is passed to the centralized error handler middleware, which sends the error response.
Execution Sample
Express
app.get('/user', (req, res, next) => {
  if (!req.query.id) {
    next(new Error('ID missing'));
  } else {
    res.send('User found');
  }
});

app.use((err, req, res, next) => {
  res.status(400).send(err.message);
});
This code checks if the query has an id. If not, it sends an error to the centralized error handler which returns a 400 status with the error message.
Execution Table
StepActionConditionResultNext
1Request to /user without idid missing?YesCall next(error)
2next(error) calledError passed to middleware?YesCentralized error handler runs
3Error handler runsSend response with error messageStatus 400, message 'ID missing'Response sent
4Request to /user with idid missing?NoSend 'User found' response
5Response sentEnd of requestSuccessRequest complete
💡 Execution stops after sending response either from route or error handler.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
req.query.idundefined or valueundefined (missing) or valueundefined (error passed) or valueunchangedunchanged
errornoneError('ID missing') created or nonepassed to error handler or nonehandled or nonenone
res.statusCode200 default200400 if error400 or 200final status sent
res.bodyempty'User found' or emptyerror message or 'User found'sent responsesent response
Key Moments - 3 Insights
Why do we call next(error) instead of sending response directly in the route?
Calling next(error) passes the error to the centralized error handler middleware, keeping error handling in one place. See execution_table step 2 where next(error) triggers the error handler.
What happens if the route sends a response without calling next(error)?
The centralized error handler is not called. The response is sent immediately as in execution_table step 4 and 5.
Why does the error handler have four parameters (err, req, res, next)?
Express recognizes middleware with four parameters as error handlers. This lets Express route errors to this middleware, as shown in the concept_flow and execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the status code sent when an error occurs?
A400
B200
C500
D404
💡 Hint
Check execution_table row 3 where the error handler sends the response.
At which step does the centralized error handler middleware run?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
See execution_table where error handler sends the error response.
If the route always sends a response without calling next(error), what changes in the execution table?
AError handler runs anyway
Bnext(error) is never called, error handler skipped
CStatus code changes to 500
DRequest never completes
💡 Hint
Look at execution_table step 4 and 5 where no error is passed.
Concept Snapshot
Centralized error handler in Express:
- Use next(error) in routes to pass errors
- Define error handler middleware with 4 params: (err, req, res, next)
- Error handler sends error response centrally
- Keeps error handling consistent and clean
- Middleware order matters: error handler last
Full Transcript
In Express, when a request comes in, the route handler runs. If an error happens, instead of sending a response immediately, the route calls next(error). This passes the error to a special middleware called the centralized error handler, which has four parameters: err, req, res, next. This middleware sends a response with the error message and status code. If no error occurs, the route sends the normal response. This keeps error handling in one place and makes code cleaner. The error handler middleware must be added after all routes. The execution table shows the steps: request received, error detected, next(error) called, error handler runs, response sent. Variables like req.query.id, error, res.statusCode, and res.body change accordingly during these steps.