Create a Custom API Error Class

As an application grows, different services may produce different kinds of errors.

For example:

  • User not found.
  • Invalid credentials.
  • Duplicate email.
  • Permission denied.
  • Invalid request.

Create a reusable custom error class so the application can carry an HTTP status code and a safe error message.

src/utils/app-error.js
export class AppError extends Error {
  constructor(message, statusCode = 500) {
    super(message);

    this.statusCode = statusCode;
    this.isOperational = true;

    Error.captureStackTrace(this, this.constructor);
  }
}

Creates an application error that contains a message, HTTP status code, and operational error indicator.

Key Takeaways
  • Custom errors represent expected application failures.

  • HTTP status codes can travel with errors.

  • Error classes make centralized handling easier.