Bird
Raised Fist0
Expressframework~10 mins

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

Choose your learning style10 modes available
Concept Flow - Error-handling middleware
Request received
↓
Route handler runs
↓
Error occurs?
No→Send response
Yes↓
Pass error to next()
↓
Error-handling middleware runs
↓
Send error response
↓
End request
When a request causes an error, Express passes it to special middleware with 4 parameters to handle and respond with error info.
Execution Sample
Express
app.use((err, req, res, next) => {
  console.error(err.message);
  res.status(500).send('Server error');
});
This middleware catches errors, logs the message, and sends a 500 response.
Execution Table
StepActionError Present?Middleware CalledResponse Sent
1Request received at /dataNoRoute handlerNo
2Route handler runsYes (throws error)Route handlerNo
3Error passed to next()YesError-handling middlewareNo
4Error-handling middleware logs errorYesError-handling middlewareNo
5Error-handling middleware sends 500 responseYesError-handling middleware500 Server error
6Request endsNoNoneResponse sent
💡 Error handled and response sent, request cycle ends.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5
errundefinedError object with message 'Something broke!'Same error objectSame error object
res.statusCode200 (default)200 (default)200 (default)500
responseSentfalsefalsefalsetrue
Key Moments - 2 Insights
Why does error-handling middleware have 4 parameters instead of 3?
Express identifies error-handling middleware by the 4 parameters (err, req, res, next). This lets it run only when an error is passed, as shown in steps 3-5.
What happens if next() is called without an error in error-handling middleware?
If next() is called without an error, Express skips error middleware and looks for normal middleware, which can cause the error to be unhandled. See step 3 where next(err) is used to pass the error.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step does the error-handling middleware first run?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Check the 'Middleware Called' column to see when error-handling middleware starts.
According to the variable tracker, what is the response status code after step 5?
A500
B200
C404
Dundefined
💡 Hint
Look at the 'res.statusCode' row after step 5.
If the route handler did not throw an error, what would happen according to the flow?
AError-handling middleware runs anyway
Bnext(err) is called with undefined
CRequest ends after sending normal response
DServer crashes
💡 Hint
Refer to the concept flow where 'Error occurs?' is No.
Concept Snapshot
Error-handling middleware in Express:
- Has 4 parameters: (err, req, res, next)
- Runs only when next(err) is called
- Used to catch errors and send error responses
- Place after all other middleware
- Example: app.use((err, req, res, next) => { res.status(500).send('Error'); })
Full Transcript
In Express, error-handling middleware is special middleware with four parameters: err, req, res, and next. When a route handler or middleware calls next() with an error, Express skips normal middleware and runs error-handling middleware. This middleware can log the error and send a response like a 500 status code. The flow starts with a request, runs the route handler, and if an error occurs, passes it to error middleware which sends the error response. Variables like the error object and response status code change during this process. Understanding when error middleware runs and how it handles errors helps keep your app stable and user-friendly.

Practice

(1/5)
1. What is the main purpose of error-handling middleware in Express?
easy
A. To serve static files like images and CSS
B. To parse incoming JSON request bodies
C. To catch errors and prevent the server from crashing
D. To log every request made to the server

Solution

  1. Step 1: Understand middleware roles

    Middleware can serve many roles, but error-handling middleware specifically catches errors.
  2. Step 2: Identify error-handling middleware purpose

    Error-handling middleware prevents the server from crashing by catching errors and responding properly.
  3. Final Answer:

    To catch errors and prevent the server from crashing -> Option C
  4. Quick Check:

    Error-handling middleware = catch errors [OK]
Hint: Error middleware catches errors to keep server running [OK]
Common Mistakes:
  • Confusing error middleware with static file serving
  • Thinking it parses request bodies
  • Assuming it logs requests
2. Which of the following is the correct signature for an Express error-handling middleware function?
easy
A. (err, req, res, next)
B. (req, res, next)
C. (req, res)
D. (err, res, next)

Solution

  1. Step 1: Recall error middleware parameters

    Error-handling middleware always has four parameters: err, req, res, next.
  2. Step 2: Match the correct parameter order

    Only (err, req, res, next) has all four parameters in the correct order.
  3. Final Answer:

    (err, req, res, next) -> Option A
  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
  • Omitting the err parameter
  • Wrong parameter order
3. Given the code below, what will be the response if an error occurs in the route?
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  throw new Error('Oops!');
});

app.use((err, req, res, next) => {
  res.status(500).send('Error caught: ' + err.message);
});

app.listen(3000);
medium
A. The client receives 'Error caught: Oops!' with status 500
B. The server crashes and stops running
C. The client receives a 404 Not Found error
D. The client receives an empty response with status 200

Solution

  1. Step 1: Identify error thrown in route

    The route throws an error with message 'Oops!'.
  2. Step 2: Check error-handling middleware response

    The error middleware catches the error and sends a 500 status with message including 'Oops!'.
  3. Final Answer:

    The client receives 'Error caught: Oops!' with status 500 -> Option A
  4. Quick Check:

    Error thrown = caught and sent with 500 [OK]
Hint: Thrown errors go to error middleware response [OK]
Common Mistakes:
  • Expecting server crash on error
  • Confusing 404 with error response
  • Missing error message in response
4. What is wrong with the following error-handling middleware?
app.use((req, res, next, err) => {
  res.status(500).send('Error: ' + err.message);
});
medium
A. It should be placed before routes
B. The parameters are in the wrong order
C. It is missing the next() call
D. It should not have four parameters

Solution

  1. Step 1: Check parameter order for error middleware

    Error middleware must have parameters in order: err, req, res, next.
  2. Step 2: Identify incorrect order in code

    The code has (req, res, next, err) which is incorrect.
  3. Final Answer:

    The parameters are in the wrong order -> Option B
  4. Quick Check:

    Error middleware params order = err, req, res, next [OK]
Hint: Error middleware params start with err, not req [OK]
Common Mistakes:
  • Swapping err and req parameters
  • Placing error middleware before routes
  • Forgetting to call next() when needed
5. You want to create an error-handling middleware that logs the error message and then passes the error to the next middleware. Which of the following implementations is correct?
A) app.use((err, req, res, next) => {
  console.log(err.message);
  next(err);
});

B) app.use((req, res, next, err) => {
  console.log(err.message);
  next();
});

C) app.use((err, req, res) => {
  console.log(err.message);
  next(err);
});

D) app.use((err, req, res, next) => {
  console.log(err.message);
  res.send('Error logged');
});
hard
A. app.use((err, req, res, next) => { console.log(err.message); res.send('Error logged'); });
B. app.use((req, res, next, err) => { console.log(err.message); next(); });
C. app.use((err, req, res) => { console.log(err.message); next(err); });
D. app.use((err, req, res, next) => { console.log(err.message); next(err); });

Solution

  1. Step 1: Recall requirements for error-handling middleware that chains

    It must have four parameters starting with err, log err.message, and call next(err) to pass the error to the next handler.
  2. Step 2: Match against provided implementations

    Implementations with incorrect parameter order or count fail to receive or handle err properly; those that respond instead of calling next(err) break the chain.
  3. Final Answer:

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

    4 params + next(err) = correct chaining [OK]
Hint: Error middleware must have 4 params and call next(err) to continue [OK]
Common Mistakes:
  • Wrong parameter order
  • Forgetting next parameter
  • Not calling next(err) to pass error along
  • Sending response too early
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