0
0
Expressframework~10 mins

Custom error classes in Express - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Custom error classes
Define Custom Error Class
Throw Custom Error in Route
Express Error Middleware Catches Error
Send Custom Error Response to Client
This flow shows how to create a custom error class, throw it in a route, catch it in Express error middleware, and send a response.
Execution Sample
Express
class NotFoundError extends Error {
  constructor(message) {
    super(message);
    this.name = 'NotFoundError';
    this.statusCode = 404;
  }
}

app.get('/item/:id', (req, res, next) => {
  if (!db.has(req.params.id)) {
    return next(new NotFoundError('Item not found'));
  }
  res.send(db.get(req.params.id));
});
Defines a custom error class and uses it in an Express route to handle missing items.
Execution Table
StepActionError InstanceMiddleware CalledResponse Sent
1Request to /item/123NoneNoNo
2Check if item exists in dbNoneNoNo
3Item not found, create NotFoundErrorNotFoundError('Item not found')NoNo
4Call next() with errorNotFoundError('Item not found')YesNo
5Error middleware receives NotFoundErrorNotFoundError('Item not found')YesNo
6Send response with status 404 and messageNotFoundError('Item not found')YesYes
7Request ends with 404 responseNoneNoYes
💡 Response sent with 404 status because item was not found.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
errorundefinedNotFoundError('Item not found')NotFoundError('Item not found')undefined
Key Moments - 2 Insights
Why do we call next() with the error instead of sending a response directly?
Calling next(error) passes the error to Express error middleware, which centralizes error handling. See execution_table step 4 and 5.
What is the purpose of setting this.name and this.statusCode in the custom error?
this.name helps identify the error type, and this.statusCode lets middleware send the correct HTTP status. See execution_sample code.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step does Express error middleware first handle the error?
AStep 3
BStep 5
CStep 4
DStep 6
💡 Hint
Check the 'Middleware Called' column in the execution_table.
According to variable_tracker, what is the value of 'error' after step 4?
ANotFoundError('Item not found')
Bundefined
Cnull
DError('Generic error')
💡 Hint
Look at the 'After Step 4' column for 'error' in variable_tracker.
If we did not set this.statusCode in the custom error, what would likely happen?
AThe error would not be caught by middleware
BExpress would send a 404 status anyway
CExpress would send a default 500 status
DThe server would crash
💡 Hint
Think about default HTTP status codes when no statusCode is set.
Concept Snapshot
Custom error classes extend Error to add properties like statusCode.
Throw them in routes with next(error) to trigger Express error middleware.
Middleware reads error properties to send proper HTTP responses.
This centralizes error handling and keeps routes clean.
Full Transcript
This visual execution trace shows how to create and use custom error classes in Express. First, a custom error class NotFoundError is defined extending the built-in Error class, adding a statusCode property. When a request comes in for an item, the route checks if the item exists. If not, it creates a NotFoundError instance and calls next() with it. Express then calls the error-handling middleware, which reads the error's statusCode and message to send a 404 response to the client. The variable tracker shows the error variable holding the NotFoundError instance during middleware handling. Key moments clarify why next(error) is used and why setting statusCode matters. The quiz tests understanding of middleware timing, variable state, and default error behavior.