Overview
Domain Exceptions are specialized error classes that represent business rule violations and domain-specific error conditions. They provide meaningful error messages and error codes that can be handled appropriately by the application layer.Key Characteristics
- Business-Focused: Represent domain rule violations, not technical errors
- Descriptive: Provide clear, meaningful error messages
- Error Codes: Include machine-readable error codes
- Hierarchy: Organized in inheritance hierarchies
- Self-Documenting: Exception names clearly describe the error
- Type-Safe: Allow specific exception handling
Exception Structure
Domain exceptions in Soft-Bee API follow this pattern:Real Example: Auth Exceptions
The auth feature demonstrates a complete exception hierarchy:src/features/auth/domain/exceptions/auth_exceptions.py.
Exception Design Principles
1. Base Exception Per Domain
Create a base exception for each domain:2. Specific Exceptions
Create specific exceptions for each error type:3. Error Codes
Use consistent, uppercase error codes:4. Default Messages
Provide sensible default messages:5. Inheritance Hierarchy
Organize exceptions in logical hierarchies:Using Exceptions in Domain Layer
In Value Objects
Validate and throw exceptions:src/features/auth/domain/value_objects/email.py:12.
In Entities
Validate business rules:src/features/auth/domain/entities/user.py:31.
In Application Services
Handle domain logic errors:Creating New Domain Exceptions
Step 1: Create Base Exception
Step 2: Define Specific Exceptions
Step 3: Use in Domain Logic
Exception Categories
Validation Exceptions
Invalid input or data:Not Found Exceptions
Requested resource doesn’t exist:Business Rule Exceptions
Business logic violations:Authorization Exceptions
Permission or access violations:State Exceptions
Invalid state transitions:Best Practices
Use Descriptive Names
Provide Context in Messages
Use Consistent Error Codes
Catch Specific Exceptions
Don’t Swallow Exceptions
Include Additional Context When Useful
Handling Exceptions in Presentation Layer
Map domain exceptions to HTTP responses:Related Documentation
- Domain Entities - Entity validation
- Value Objects - Value object validation
- Domain Events - Event-driven architecture