Skip to content

Introduce Custom Error Classes with Error Codes #95

@sirtimid

Description

@sirtimid

Currently we handle errors using console.error and throw new Error often converting data to strings for logging. This works but has some problems: it’s hard to track errors and messages can change over time. To fix this we should create custom error classes with unique error codes. This will make error handling more consistent and easier to manage.

Plan

  • Create Error Classes: We'll introduce custom error classes for different error cases in the code. Each class will come from a main BaseError class so they all work the same way (e.g., with name, code, message, and data).

  • Use Error Codes: Each error class will have a unique error code. This code won’t change even if the error message changes making it easier to identify the exact error.

  • Centralize Errors: Put all the error classes and codes in one place (a new package) so it's easy to find and update them.

  • Improve Logging: Replace all console.error and throw new Error statements with the new error classes. This way our logs will have clear error codes, making it simpler to find and fix issues.

  • Keep Current Errors: Make sure existing errors are moved to this new system but keep their original meaning and details, now with an error code.

Steps

  1. Create the BaseError class and other error classes with their codes.
  2. Update the code in all files to use these new error classes.
  3. Adjust existing tests to work with the new error structure.

By making this change our error handling will be more organized and easier to maintain, helping us find and fix problems faster.

Example

class BaseError extends Error {
  public code: string;
  public data?: any;

  constructor(code: string, message: string, data?: any) {
    super(message);
    this.code = code;
    this.data = data;
    this.name = this.constructor.name;
  }
}

export class VatAlreadyExistsError extends BaseError {
  constructor(vatId: string) {
    super(
      'VAT_ALREADY_EXISTS',
      `Vat with ID ${vatId} already exists.`,
      { vatId }
    );
  }
}

export class VatNotFoundError extends BaseError {
  constructor(vatId: string) {
    super(
      'VAT_NOT_FOUND',
      `Vat with ID ${vatId} does not exist.`,
      { vatId }
    );
  }
}

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions