

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Error-Handling Middleware
incomplete
2: Custom Errors
incomplete
This lesson's interactive features are locked, please to keep using them
One of the few times when inheritance is a good idea is when creating custom error classes. By extending the built-in Error class, we can create custom error types that are easy to identify and handle within our application.
Here's a simple example of a NotFoundError class
class NotFoundError extends Error {
constructor(message: string) {
super(message);
}
}
super(message) so the base Error class can initialize its properties.In the error handler, we can check the error type and handle it accordingly.
function errorMiddleware(
err: Error,
req: Request,
res: Response,
next: NextFunction,
) {
if (err instanceof NotFoundError) {
res.status(404).json({ error: err.message });
} else {
res.status(500).json({ error: "Something went wrong on our end" });
}
}
A NotFoundError is much clearer than a generic Error. When we see a NotFoundError, we know that something wasn't found. We can handle it differently than a ValidationError or PermissionError.
Create some custom error classes for your application. The most common error responses are 400, 401, 403, 404. Create a class for each of these.
Do not send error messages to the client that didn't originate from a custom error. These should just be logged and treated as 500 - Internal Server Errors
Run and submit the CLI tests.