We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Custom Errors

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);
  }
}
  • We call 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" });
  }
}

Why Create Custom Errors?

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.

Assignment

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.