Bird
Raised Fist0
Expressframework~10 mins

Error-handling middleware signature in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Error-handling middleware signature
Request received
↓
Middleware chain
↓
Error occurs?
No→Next middleware
Yes↓
Error-handling middleware
↓
Send error response
↓
End request
This flow shows how Express passes requests through middleware and routes, and when an error occurs, it jumps to the error-handling middleware to send a response.
Execution Sample
Express
app.use((err, req, res, next) => {
  console.error(err.message);
  res.status(500).send('Something broke!');
});
This code defines an error-handling middleware that logs the error message and sends a 500 response.
Execution Table
StepMiddleware TypeArgumentsError Present?Action TakenResponse Sent
1Normal middleware(req, res, next)NoCall next middlewareNo
2Route handler(req, res, next)Yes (error passed)Skip to error middlewareNo
3Error-handling middleware(err, req, res, next)YesLog error and send 500 responseYes: 'Something broke!'
4End--Request ends after responseYes
💡 Error-handling middleware sends response, stopping further middleware.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
errundefinedundefinedError objectError objectError object
reqRequest objectRequest objectRequest objectRequest objectRequest object
resResponse objectResponse objectResponse objectResponse object with status 500Response sent
nextFunctionFunctionFunctionFunctionNot called after error middleware
Key Moments - 2 Insights
Why does error-handling middleware have four arguments instead of three?
Because Express identifies error-handling middleware by the presence of the first 'err' argument, as shown in the execution_table step 3 where the middleware signature is (err, req, res, next).
What happens if you forget to include the 'err' parameter in error middleware?
Express will treat it as normal middleware and not call it on errors, so errors won't be handled properly, as seen in step 2 where error skips normal middleware.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does Express detect an error and jump to error-handling middleware?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Check the 'Error Present?' and 'Action Taken' columns in execution_table rows.
According to variable_tracker, what is the value of 'err' after Step 1?
AError object
Bundefined
Cnull
DString message
💡 Hint
Look at the 'err' row under 'After Step 1' in variable_tracker.
If the error-handling middleware did not call res.status(500).send(), what would happen?
AThe request would hang without response
BExpress would automatically send a 404 response
CThe next middleware would handle the error
DThe error would be ignored and request continues
💡 Hint
Refer to execution_table step 3 and step 4 about response sending and request ending.
Concept Snapshot
Error-handling middleware in Express has 4 arguments: (err, req, res, next).
It catches errors passed from previous middleware or routes.
Use it to log errors and send error responses.
If missing 'err', Express won't treat it as error middleware.
Always end with sending a response or calling next(err).
Full Transcript
In Express, error-handling middleware is special because it has four parameters: err, req, res, and next. When an error happens in normal middleware or routes, Express skips normal middleware and jumps to the error-handling middleware. This middleware can log the error and send a response like status 500. If you forget the 'err' parameter, Express won't recognize it as error middleware, so errors won't be caught properly. The flow starts with request, goes through middleware, and if an error occurs, it jumps to error middleware which sends the response and ends the request.

Practice

(1/5)
1. Which of the following correctly describes the signature of an error-handling middleware function in Express?
easy
A. It has five parameters: err, req, res, next, done.
B. It has three parameters: req, res, next.
C. It has two parameters: req, res.
D. It has four parameters: err, req, res, next.

Solution

  1. Step 1: Recall Express middleware function signatures

    Normal middleware functions have three parameters: req, res, next. Error-handling middleware must have four parameters.
  2. Step 2: Identify the error-handling middleware signature

    Error-handling middleware functions always start with err as the first parameter, followed by req, res, next.
  3. Final Answer:

    It has four parameters: err, req, res, next. -> Option D
  4. Quick Check:

    Error middleware signature = err, req, res, next [OK]
Hint: Error middleware always has 4 parameters starting with err [OK]
Common Mistakes:
  • Using only three parameters for error middleware
  • Forgetting the err parameter at the start
  • Adding extra parameters beyond four
2. Which of the following is the correct syntax to define an error-handling middleware in Express?
easy
A. app.use(function(req, res, next, err) { /* code */ });
B. app.use(function(err, req, res, next) { /* code */ });
C. app.use(function(err, req, next, res) { /* code */ });
D. app.use(function(req, err, res, next) { /* code */ });

Solution

  1. Step 1: Check parameter order in error middleware

    The correct order is err, req, res, next. This order is required by Express to recognize error middleware.
  2. Step 2: Match the correct syntax

    app.use(function(err, req, res, next) { /* code */ }); matches the correct order and syntax for error-handling middleware.
  3. Final Answer:

    app.use(function(err, req, res, next) { /* code */ }); -> Option B
  4. Quick Check:

    Correct parameter order = err, req, res, next [OK]
Hint: Error middleware params start with err, then req, res, next [OK]
Common Mistakes:
  • Placing err parameter last or in the wrong position
  • Swapping req and res parameters
  • Using incorrect function parameter count
3. What will happen when this Express error-handling middleware is added?
app.use(function(err, req, res, next) {
  res.status(500).send('Error: ' + err.message);
});
medium
A. It catches errors and sends a 500 status with the error message.
B. It ignores errors and passes them to the next middleware.
C. It causes a syntax error because of missing next() call.
D. It crashes the app because error middleware must call next().

Solution

  1. Step 1: Understand error middleware behavior

    Error-handling middleware catches errors passed by previous middleware or routes.
  2. Step 2: Analyze the middleware code

    This middleware sends a 500 status and the error message as a response, handling the error gracefully.
  3. Final Answer:

    It catches errors and sends a 500 status with the error message. -> Option A
  4. Quick Check:

    Error middleware sends 500 and message = It catches errors and sends a 500 status with the error message. [OK]
Hint: Error middleware sends response with status 500 and error message [OK]
Common Mistakes:
  • Thinking next() must always be called in error middleware
  • Assuming error middleware crashes app without next()
  • Confusing error middleware with normal middleware
4. Identify the error in this Express error-handling middleware:
app.use(function(req, res, next, err) {
  console.error(err);
  res.status(500).send('Server error');
});
medium
A. Error middleware cannot use console.error().
B. Missing call to next() inside the middleware.
C. The parameters are in the wrong order; err must be first.
D. res.status(500) is invalid inside error middleware.

Solution

  1. Step 1: Check parameter order for error middleware

    Error-handling middleware must have parameters in order: err, req, res, next. Here, err is last, which is incorrect.
  2. Step 2: Understand impact of wrong parameter order

    Express will not recognize this as error middleware, so errors won't be caught properly.
  3. Final Answer:

    The parameters are in the wrong order; err must be first. -> Option C
  4. Quick Check:

    err parameter must be first in error middleware [OK]
Hint: Error middleware must start with err parameter [OK]
Common Mistakes:
  • Placing err parameter anywhere but first
  • Assuming next() call is mandatory in all error middleware
  • Confusing error middleware with normal middleware signature
5. You want to create an error-handling middleware that logs the error and sends a JSON response with status 500. Which of the following is the best correct implementation?
hard
A. app.use((err, req, res, next) => { console.log(err); res.status(500).json({error: err.message}); });
B. app.use((req, res, next, err) => { console.log(err); res.status(500).json({error: err.message}); });
C. app.use((err, req, res) => { console.log(err); res.status(500).json({error: err.message}); });
D. app.use((err, req, res, next) => { console.log(err); res.json({error: err.message}); });

Solution

  1. Step 1: Verify parameter count and order

    Error middleware must have exactly four parameters in order: err, req, res, next. app.use((err, req, res, next) => { console.log(err); res.status(500).json({error: err.message}); }); matches this.
  2. Step 2: Check response status and format

    app.use((err, req, res, next) => { console.log(err); res.status(500).json({error: err.message}); }); sets status 500 and sends JSON with error message, which is correct and user-friendly.
  3. Final Answer:

    app.use((err, req, res, next) => { console.log(err); res.status(500).json({error: err.message}); }); -> Option A
  4. Quick Check:

    Correct signature + status 500 + JSON response = app.use((err, req, res, next) => { console.log(err); res.status(500).json({error: err.message}); }); [OK]
Hint: Error middleware needs 4 params and sets status before sending JSON [OK]
Common Mistakes:
  • Wrong parameter order or count
  • Forgetting to set status code
  • Sending response without JSON format
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard