0
0
Node.jsframework~10 mins

Error-handling middleware in Node.js - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Error-handling middleware
Request Received
Middleware 1 Executes
Middleware 2 Executes
Error Occurs?
NoNext Middleware or Response
Yes
Error-handling Middleware Executes
Send Error Response
End
The request passes through normal middleware until an error occurs, then error-handling middleware runs to send an error response.
Execution Sample
Node.js
app.use((req, res, next) => {
  if (!req.user) {
    next(new Error('No user'));
  } else {
    next();
  }
});

app.use((err, req, res, next) => {
  res.status(500).send(err.message);
});
This code checks if a user exists; if not, it passes an error to the error handler which sends a 500 response.
Execution Table
StepMiddleware TypeInputActionNext Step
1Normal MiddlewareRequest with no userChecks req.user, finds noneCalls next(error) with Error('No user')
2Error-handling MiddlewareError('No user')Sends 500 status and error messageResponse sent, ends request
3Normal MiddlewareRequest with userCalls next() without errorPasses to next middleware or response
4No more middlewareNo errorSends normal responseEnds request
💡 Execution stops after error-handling middleware sends response or after normal middleware completes response.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
req.userundefined or objectundefined (no user) or object (user)unchangedunchangedunchanged
errnoneError('No user') if no user, else nonepassed to error handler or nonenonenone
res.statusCode200 (default)200500 if error sent200200
Key Moments - 3 Insights
Why does the error-handling middleware have 4 parameters (err, req, res, next)?
Because Express identifies error-handling middleware by the presence of 4 parameters. This middleware runs only when next() is called with an error, as shown in step 2 of the execution_table.
What happens if next() is called without an error?
The request continues to the next normal middleware or response, as shown in step 3 and 4 of the execution_table.
Can normal middleware send a response after calling next(error)?
No, once next(error) is called, Express skips normal middleware and goes directly to error-handling middleware, which sends the response (step 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens at step 2?
ANormal middleware processes the request
BError-handling middleware sends a 500 response
CRequest is passed to the next normal middleware
DThe server crashes
💡 Hint
Check the 'Action' column at step 2 in the execution_table.
At which step does the middleware detect there is no user in the request?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Input' and 'Action' columns in the execution_table for step 1.
If req.user exists, what will be the status code after all middleware run?
A500
B404
C200
D401
💡 Hint
Check the variable_tracker for res.statusCode after step 4.
Concept Snapshot
Error-handling middleware in Node.js Express has 4 parameters: (err, req, res, next).
It runs only when next() is called with an error.
Normal middleware calls next() to continue or next(error) to trigger error handling.
Error middleware sends error responses, stopping normal flow.
Always place error middleware after normal middleware.
Full Transcript
In Node.js Express, error-handling middleware is special middleware that runs only when an error occurs. It has four parameters: error, request, response, and next. When normal middleware detects a problem, it calls next with an error. This skips all normal middleware and runs the error handler. The error handler sends a response with an error message and status code, usually 500. If no error occurs, normal middleware calls next without arguments to continue processing. This flow ensures errors are caught and handled cleanly without crashing the server.