📖 Scenario: You are building a simple Express server that handles user requests. You want to create custom error classes to manage different error types clearly and send proper responses.
🎯 Goal: Create custom error classes for NotFoundError and ValidationError, then use them in an Express route to handle errors properly.
📋 What You'll Learn
Create a base error class called AppError that extends Error
Create a NotFoundError class that extends AppError with a default message
Create a ValidationError class that extends AppError with a default message
Use these custom errors in an Express route and handle them in error middleware
💡 Why This Matters
🌍 Real World
Custom error classes help organize error handling in web servers, making it easier to send clear messages to users and debug issues.
💼 Career
Understanding custom errors and middleware is essential for backend developers working with Express or similar frameworks to build robust APIs.
Progress0 / 4 steps
1
Create the base error class
Create a class called AppError that extends the built-in Error class. It should accept message and statusCode parameters in the constructor and set them as properties.
Express
Hint
Remember to call super(message) inside the constructor to set the error message.
2
Create NotFoundError and ValidationError classes
Create two classes: NotFoundError and ValidationError. Both should extend AppError. The NotFoundError constructor should call super with message 'Resource not found' and status code 404. The ValidationError constructor should call super with message 'Invalid input' and status code 400.
Express
Hint
Use super in each constructor to pass the message and status code to AppError.
3
Use custom errors in an Express route
Create an Express app. Add a GET route at /items/:id. Inside the route, if req.params.id is not '1', throw a NotFoundError. Otherwise, send JSON { id: '1', name: 'Item One' }.
Express
Hint
Use next() to pass the error to Express error handlers.
4
Add error handling middleware
Add an Express error-handling middleware function that takes err, req, res, next. If err is an instance of AppError, respond with err.statusCode and JSON { error: err.message }. Otherwise, respond with status 500 and JSON { error: 'Internal Server Error' }. Export the app.
Express
Hint
Error middleware in Express has four parameters. Use instanceof to check error type.
Practice
(1/5)
1. What is the main purpose of creating a custom error class in an Express application?
easy
A. To define specific error types with custom messages and status codes
B. To replace the Express framework's built-in error handling completely
C. To avoid using try-catch blocks in asynchronous code
D. To automatically fix errors in the application code
Solution
Step 1: Understand the role of custom error classes
Custom error classes extend the built-in Error class to represent specific error types with meaningful messages and HTTP status codes.
Step 2: Compare with other options
Custom errors do not replace Express error handling but improve it; they do not fix code automatically or remove the need for try-catch.
Final Answer:
To define specific error types with custom messages and status codes -> Option A
Quick Check:
Custom error classes = specific error types [OK]
Hint: Custom errors add meaning and status codes to errors [OK]
Common Mistakes:
Thinking custom errors fix bugs automatically
Believing they replace Express error middleware
Assuming they remove try-catch necessity
2. Which of the following is the correct way to define a custom error class named NotFoundError that sets a 404 status code?
easy
A. function NotFoundError() { this.message = 'Not Found'; this.status = 404; }
B. class NotFoundError extends Error { constructor() { this.message = 'Not Found'; this.status = 404; } }
C. class NotFoundError { constructor() { this.message = 'Not Found'; this.status = 404; } }
D. class NotFoundError extends Error { constructor() { super('Not Found'); this.status = 404; } }
Solution
Step 1: Check class inheritance and constructor
The custom error class must extend Error and call super() with the message to set the error message properly.
Step 2: Verify setting status property
Setting this.status = 404 inside the constructor is correct for HTTP status code.
Final Answer:
class NotFoundError extends Error { constructor() { super('Not Found'); this.status = 404; } } -> Option D
A. Constructor should not accept message parameter
B. Status code 401 is invalid for authentication errors
C. Missing call to super(message) in constructor
D. Class should not extend Error for custom errors
Solution
Step 1: Check constructor of subclass of Error
When extending Error, the constructor must call super(message) to properly initialize the error message.
Step 2: Identify missing super call
The code sets this.message directly but does not call super(), which causes errors in Error inheritance.
Final Answer:
Missing call to super(message) in constructor -> Option C
Quick Check:
Always call super(message) in Error subclass constructor [OK]
Hint: Always call super() first in Error subclass constructor [OK]
Common Mistakes:
Setting this.message without super()
Forgetting to extend Error
Using wrong status codes for errors
5. You want to create a custom error class DatabaseError that accepts a message and an optional error code, defaulting to 500. Which implementation correctly supports this and sets both status and code properties?
hard
A. class DatabaseError extends Error {
constructor(message, code = 500) {
super(message);
this.status = code;
this.code = 500;
}
}