0
0
Expressframework~30 mins

Custom error classes in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Error Classes in Express
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Error middleware in Express has four parameters. Use instanceof to check error type.