Skip to content

Fix: migrate domain specific errors into their module#137

Merged
Villarley merged 1 commit intoVolunChain:mainfrom
od-hunter:fix/migrate
Jul 8, 2025
Merged

Fix: migrate domain specific errors into their module#137
Villarley merged 1 commit intoVolunChain:mainfrom
od-hunter:fix/migrate

Conversation

@od-hunter
Copy link
Copy Markdown
Contributor

@od-hunter od-hunter commented Jun 29, 2025

🚀 Volunchain Pull Request

Mark with an x all the checkboxes that apply (like [x])


📌 Type of Change

  • Documentation (updates to README, docs, or comments)
  • Bug fix (non-breaking change which fixes an issue)
  • Enhancement (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

📝 Changes description

I successfully migrated all domain-specific errors from the legacy src/errors/ directory to their appropriate modules under the new architecture.


📸 Evidence (A photo is required as evidence)


⏰ Time spent breakdown

4 hours


🌌 Comments


Thank you for contributing to Volunchain, we are glad that you have chosen us as your project of choice and we hope that you continue to contribute to this great project, so that together we can make our mark at the top!

Summary by CodeRabbit

  • Refactor

    • Centralized and reorganized error class exports for easier imports across the application.
    • Updated error class inheritance to use domain-specific base exceptions.
    • Adjusted import paths for error classes throughout the codebase for consistency.
  • Tests

    • Added comprehensive tests for custom error classes, including volunteer registration and shared errors, ensuring correct behavior, inheritance, and serialization.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jun 29, 2025

Walkthrough

The changes introduce new and refactored test suites for error classes, centralize and update error-related exports, and adjust import paths across the codebase to use new module locations. Error class hierarchies are updated to inherit from a domain-specific exception base, and new index files are added for organized error exports.

Changes

File(s) Change Summary
tests/application/errors/common.errors.test.ts,
tests/application/errors/volunteer-registration.errors.test.ts
New test suites for verifying custom error classes and constants, including instantiation, inheritance, serialization, and async behavior.
src/modules/shared/application/errors/common.errors.ts,
src/modules/volunteer/application/errors/volunteer-registration.errors.ts
Error classes refactored to extend from a domain-specific DomainException instead of Error; property assignments updated.
src/modules/shared/application/errors/index.ts,
src/modules/volunteer/application/errors/index.ts
New index files added to centralize and re-export error classes and constants for easier imports.
src/middlewares/errorHandler.ts,
src/services/OrganizationService.ts,
src/services/ProjectService.ts,
src/services/userVolunteer.service.ts,
src/services/tests/userVolunteer.service.test.ts,
tests/middlewares/errorHandler.test.ts
Updated import paths for error classes to reference new module locations; no logic changes.

Sequence Diagram(s)

sequenceDiagram
    participant Service
    participant ErrorClass
    participant DomainException

    Service->>ErrorClass: throw new CustomError(...)
    ErrorClass->>DomainException: super(message)
    DomainException-->>ErrorClass: initialize base properties
    ErrorClass-->>Service: error instance created with code, statusCode, details
    Service->>Service: catch CustomError and handle
Loading
sequenceDiagram
    participant VolunteerService
    participant VolunteerError
    participant DomainException

    VolunteerService->>VolunteerError: throw new VolunteerRegistrationError(...)
    VolunteerError->>DomainException: super(message)
    DomainException-->>VolunteerError: initialize base properties
    VolunteerError-->>VolunteerService: error instance created
    VolunteerService->>VolunteerService: catch VolunteerRegistrationError and handle
Loading

Poem

In the warren of code, where errors may roam,
We tidied their burrows and gave them a home.
From shared to volunteer, exceptions now gleam,
With tests and new exports—our error-handling dream!
🐇✨
Now bugs may appear, but we’ll catch them with cheer!

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-29T20_13_13_175Z-debug-0.log


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8444abe and 18b50ab.

📒 Files selected for processing (12)
  • __tests__/application/errors/common.errors.test.ts (1 hunks)
  • __tests__/application/errors/volunteer-registration.errors.test.ts (1 hunks)
  • src/middlewares/errorHandler.ts (1 hunks)
  • src/modules/shared/application/errors/common.errors.ts (3 hunks)
  • src/modules/shared/application/errors/index.ts (1 hunks)
  • src/modules/volunteer/application/errors/index.ts (1 hunks)
  • src/modules/volunteer/application/errors/volunteer-registration.errors.ts (1 hunks)
  • src/services/OrganizationService.ts (1 hunks)
  • src/services/ProjectService.ts (1 hunks)
  • src/services/__tests__/userVolunteer.service.test.ts (1 hunks)
  • src/services/userVolunteer.service.ts (1 hunks)
  • tests/middlewares/errorHandler.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
__tests__/application/errors/volunteer-registration.errors.test.ts (1)
src/modules/volunteer/application/errors/volunteer-registration.errors.ts (4)
  • VolunteerRegistrationError (3-7)
  • VolunteerPositionFullError (9-13)
  • VolunteerAlreadyRegisteredError (15-19)
  • VolunteerNotFoundError (21-25)
__tests__/application/errors/common.errors.test.ts (1)
src/modules/shared/application/errors/common.errors.ts (10)
  • HttpStatus (4-11)
  • ErrorCodes (14-22)
  • CustomError (24-49)
  • ValidationError (51-60)
  • DatabaseError (62-71)
  • AuthenticationError (73-82)
  • AuthorizationError (84-93)
  • ResourceNotFoundError (95-104)
  • ResourceConflictError (106-110)
  • InternalServerError (112-124)
🔇 Additional comments (31)
src/modules/volunteer/application/errors/index.ts (1)

1-6: LGTM: Clean centralized error exports

This barrel export pattern effectively centralizes volunteer-related error classes, making imports cleaner and more maintainable across the codebase.

src/modules/shared/application/errors/common.errors.ts (2)

1-1: DomainException properly extends Error and maintains prototypes
DomainException’s constructor calls super(), sets this.name, and uses Object.setPrototypeOf(this, new.target.prototype), so having CustomError extend it preserves correct instanceof behavior and stack traces. No further action needed.


24-49: No action needed: CustomError inheritance remains correct

  • DomainException (the new superclass) already calls Object.setPrototypeOf(this, new.target.prototype), ensuring the prototype chain is fixed.
  • CustomError inherits from DomainException, so
    • instanceof Error, instanceof DomainException, and instanceof CustomError all work as expected.
    • error.name and stack traces are preserved.
    • JSON.stringify(error) includes message, statusCode, errorCode, and optional details per the toJSON method.
    • The existing error-handling middleware (checking err instanceof CustomError) continues to detect and format these errors correctly.
      All relevant tests for inheritance, serialization, and middleware behavior are passing.
src/modules/shared/application/errors/index.ts (1)

1-12: LGTM: Comprehensive shared error exports

Well-organized barrel export that centralizes all shared error classes and constants, improving import consistency across the codebase.

src/services/OrganizationService.ts (1)

2-2: LGTM: Correct import path update

The import path has been properly updated to use the new centralized error exports, aligning with the modular architecture.

src/services/ProjectService.ts (1)

6-6: LGTM: Consistent import path migration

The import paths have been correctly updated to use the centralized shared error exports, maintaining consistency with the new modular structure.

src/middlewares/errorHandler.ts (1)

2-2: LGTM: Clean import path migration.

The import path update aligns with the new modular error organization structure. The middleware functionality remains unchanged, which is correct for this architectural refactoring.

tests/middlewares/errorHandler.test.ts (1)

9-9: LGTM: Consistent import path update.

The import path change is consistent with the main errorHandler middleware file, maintaining proper test coverage alignment with the new modular error structure.

src/services/__tests__/userVolunteer.service.test.ts (1)

5-5: LGTM: Domain-specific error import migration.

The import path correctly moves volunteer-related errors to their domain-specific module location, improving code organization and maintainability.

src/services/userVolunteer.service.ts (1)

6-6: LGTM: Consistent import path migration.

The import path change is consistent with the corresponding test file and properly moves volunteer errors to their domain-specific module location without affecting service functionality.

src/modules/volunteer/application/errors/volunteer-registration.errors.ts (2)

1-2: LGTM: Domain-specific error hierarchy foundation.

The import of DomainException establishes a proper domain-specific error base class, improving error handling architecture.


3-7: DomainException compatibility verified – no changes needed

DomainException in src/modules/shared/domain/exceptions/domain.exception.ts correctly extends the native Error class, sets the name property, and fixes the prototype chain via Object.setPrototypeOf. No further action is required.

__tests__/application/errors/volunteer-registration.errors.test.ts (7)

1-8: LGTM! Clean imports and proper test setup.

The imports are well-organized and correctly reference the migrated error classes and domain exception base class.


10-26: Comprehensive test coverage for base error class.

The tests properly verify the custom message functionality, inheritance chain, and error properties. Good coverage of the VolunteerRegistrationError base class.


28-44: Excellent inheritance and property validation.

The tests correctly verify both the error message from the relevant code snippet ("Volunteer position is full") and the complete inheritance chain. Good use of instanceof checks.


46-62: Proper validation of error properties and inheritance.

The test correctly validates the error message matches the implementation ("User is already registered for this volunteer position") and maintains proper inheritance hierarchy.


64-80: Good coverage of error properties and inheritance.

The test properly validates the "Volunteer position not found" message and inheritance chain, consistent with the error class implementation.


82-118: Excellent async error simulation testing.

The simulation tests provide valuable coverage by testing actual error throwing scenarios with both type and message validation. This helps ensure the errors work correctly in real async contexts.


120-138: Good coverage of error serialization and runtime behavior.

The serialization test ensures error information is preserved when serialized, and the catch block test validates real-world error handling scenarios. This complements the other test coverage well.

__tests__/application/errors/common.errors.test.ts (12)

1-14: Well-organized imports with comprehensive coverage.

The imports cleanly bring in all necessary error classes, constants, and testing utilities. Good organization separating the common errors from the domain exception base class.


16-37: Excellent constant validation coverage.

The tests properly verify all HTTP status codes and error code constants match their expected values. This ensures the constants remain consistent with standard HTTP status codes and internal error classification.


39-91: Comprehensive CustomError testing with excellent JSON serialization coverage.

The tests thoroughly cover:

  • All constructor parameters (with and without optional details)
  • Proper inheritance from DomainException
  • JSON serialization with conditional details inclusion
  • All error properties are correctly set

The JSON serialization tests are particularly valuable for API error responses.


93-116: Thorough ValidationError testing.

Tests properly validate the error code, HTTP status (400), and optional details handling. Good coverage of both constructor variants.


118-131: Proper DatabaseError validation.

Correctly tests the 500 status code assignment and error code constant usage, appropriate for database-related failures.


133-144: Good AuthenticationError coverage.

Properly validates the 401 status code and authentication error code, essential for auth-related failures.


146-157: Appropriate AuthorizationError testing.

Correctly validates the 403 status code distinction from authentication errors, important for proper HTTP semantics.


159-172: Solid ResourceNotFoundError validation.

Tests the 404 status code and demonstrates proper usage with details (userId example), good for REST API error handling.


174-185: Good ResourceConflictError coverage.

Properly tests the 409 status code for conflict scenarios, essential for handling duplicate resource creation attempts.


187-206: Excellent InternalServerError testing with default value coverage.

Tests both the default message fallback and custom message scenarios. Good coverage of the optional parameters and 500 status code assignment.


208-227: Outstanding inheritance chain and type distinction testing.

This section provides critical validation of:

  • Complete inheritance chain from specific error → CustomError → DomainException → Error
  • Type safety and distinction between different error classes
  • Proper instanceof behavior

This is excellent defensive testing for the error hierarchy.


229-256: Valuable async error simulation coverage.

The simulation tests validate that errors work correctly in promise rejection scenarios, which is essential for async/await error handling patterns commonly used in the application.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@Villarley Villarley left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Villarley Villarley merged commit abb2070 into VolunChain:main Jul 8, 2025
1 check passed
@coderabbitai coderabbitai bot mentioned this pull request Aug 26, 2025
10 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Migrate Domain-Specific Errors to Their Modules

2 participants