Structured Exceptions and Metrics
Relevant source files
The following files were used as context for generating this wiki page:
Structured Exceptions and Metrics within FLEXT-Core provide a robust framework for handling fallible operations and tracking system health through observable error states. The system centers on a unified exception hierarchy that integrates directly with Railway-Oriented Programming (ROP) patterns, allowing errors to be either raised as exceptions or returned as structured failure results.
This module ensures that every error carries mandatory metadata, including error codes, domains, and optional correlation IDs. Additionally, it provides a centralized mechanism for recording exception occurrences, enabling real-time diagnostics and health monitoring through validated metrics snapshots.
Exception Architecture
The exception system is built upon a hierarchical structure where all domain-specific errors inherit from a common BaseError. This base class enforces a structured contract, ensuring that every exception exposes consistent properties such as error_code, error_domain, and metadata.
Core Exception Hierarchy
| Component | Description |
|---|---|
BaseError | The root of the FLEXT exception hierarchy, implementing the StructuredError protocol. |
ValidationError | Raised when input data or state transitions violate domain rules. |
NotFoundError | Indicates a requested resource (e.g., user, file, record) does not exist. |
OperationError | Represents a failure in a specific business logic operation or process. |
AuthenticationError | Raised during failed identity verification attempts. |
AuthorizationError | Indicates a lack of sufficient permissions for a requested action. |
The following diagram illustrates the relationship between the base error and specialized exception types.
Structured Metrics and Tracking
The system tracks exception occurrences in real-time using a state-based metrics collector. This collector maintains counters for each unique exception type and can generate validated snapshots for external reporting or logging.
Metrics Components
- ExceptionMetricsState: An internal, copy-updated runtime state that increments counters whenever an exception is recorded.
- ExceptionMetricsSnapshot: A validated Pydantic model representing a point-in-time view of exception statistics.
- Metric Facade Methods: High-level API functions such as
record_exception,resolve_metrics_snapshot, andclear_metrics.
Exception Metrics Data Model
| Field | Type | Description |
|---|---|---|
total_exceptions | NonNegativeInt | The cumulative count of all exceptions recorded. |
unique_exception_types | NonNegativeInt | The number of distinct exception classes encountered. |
exception_counts | IntMapping | A dictionary mapping exception class names to their occurrence counts. |
exception_counts_summary | str | A human-readable string (e.g., "ValidationError:5;NotFoundError:2"). |
Sources: src/flext_core/_models/errors.py:21-41
Fail-DSL and Result Integration
FLEXT-Core provides a "Fail-DSL" via factories that convert exceptions into structured Result objects. This bridge allows developers to use ROP patterns without manually wrapping exceptions in r.fail() calls.
Failure Factories
The FlextExceptions facade (often aliased as e) includes several fail_* methods:
fail_not_found(resource_type, resource_id): Returns a failure result with aNotFoundErrorcontext.fail_auth(auth_method, user_id): Returns anAuthenticationErrorfailure result.fail_timeout(timeout_seconds, operation): Returns aTimeoutErrorfailure result.fail_conflict(resource_type, resource_id, reason): Returns aConflictErrorfailure result.
# Example of Fail-DSL usage
def get_user(user_id: str) -> p.Result[User]:
user = db.find(user_id)
if not user:
return e.fail_not_found("User", user_id)
return r.ok(user)
Sources: src/flext_core/_exceptions/factories.py, tests/unit/test_exceptions.py:134-168, tests/unit/test_exceptions_structured_contracts.py:116-133
Error Domain Routing
Exceptions are categorized into functional domains, allowing for high-level error handling strategies (e.g., retrying network errors vs. returning 400s for validation errors).
| Error Domain | Associated Exceptions |
|---|---|
VALIDATION | ValidationError |
AUTH | AuthenticationError, AuthorizationError |
NOT_FOUND | NotFoundError |
NETWORK | ConnectionError |
TIMEOUT | TimeoutError |
INTERNAL | OperationError, ConfigurationError |
Sources: tests/unit/test_exceptions.py:48-61, tests/unit/test_exceptions_structured_contracts.py:44-55
Conclusion
The "Structured Exceptions and Metrics" system provides the foundation for resilient and observable applications. By enforcing a strict error contract and providing built-in metrics, FLEXT-Core ensures that failures are not just handled, but are categorized and measured, facilitating faster debugging and better operational visibility.