elersong / fireorm24

ORM for Firebase Firestore 🔥 updated for 2024
MIT License
1 stars 0 forks source link

Refactor Error Handling #24

Open elersong opened 3 months ago

elersong commented 3 months ago

Description

Fireorm can throw different types of errors, including Firestore errors, validation errors, and other generic errors. Currently, error declarations are scattered throughout the codebase, leading to duplicated and inconsistent error handling. To improve maintainability and readability, error handling should be centralized.

Steps to Reproduce

  1. Trigger different types of errors in Fireorm.
  2. Observe the scattered and duplicated error declarations.

Expected Behavior

Centralized error handling with consistent error messages and types, reducing code duplication and improving maintainability.

Actual Behavior

Error declarations are scattered throughout the codebase, leading to duplicated and inconsistent error handling.

Acceptance Criteria

Additional Context

Proposed API Changes

  1. Centralize Error Definitions:

    • Create a centralized location for error definitions in src/Errors.
    // src/Errors/index.ts
    export class FirestoreError extends Error {
     constructor(message: string) {
       super(message);
       this.name = 'FirestoreError';
     }
    }
    
    export class ValidationError extends Error {
     constructor(message: string) {
       super(message);
       this.name = 'ValidationError';
     }
    }
    
    export class GenericError extends Error {
     constructor(message: string) {
       super(message);
       this.name = 'GenericError';
     }
    }
  2. Refactor Error Handling in Codebase:

    • Replace all instances of new Error() with the appropriate custom error classes.
    import { FirestoreError, ValidationError, GenericError } from './Errors';
    
    // Example refactoring
    try {
     // some Firestore operation
    } catch (error) {
     throw new FirestoreError('Failed to perform Firestore operation');
    }
    
    if (this.config.validateModels) {
     const errors = await validate(item);
     if (errors.length) {
       throw new ValidationError('Model validation failed');
     }
    }
    
    if (someOtherCondition) {
     throw new GenericError('An unknown error occurred');
    }
  3. Remove Duplicated Error Declarations:

    • Identify and remove any duplicated error declarations throughout the codebase.

Example Implementation

@Collection()
class User {
  @IsString()
  id: string;

  @IsString()
  display_name: string;

  @IsString()
  username: string;
}

// Repository instance
class UserRepository {
  async create(user: User) {
    try {
      // create logic
    } catch (error) {
      throw new FirestoreError('Failed to create user');
    }
  }

  async update(user: User) {
    try {
      // update logic
    } catch (error) {
      throw new FirestoreError('Failed to update user');
    }
  }
}

Original Issue