Errors
provide.foundation.errors
¶
TODO: Add module docstring.
Classes¶
AlreadyExistsError
¶
AlreadyExistsError(
message: str,
*,
resource_type: str | None = None,
resource_id: str | None = None,
**kwargs: Any
)
Bases: FoundationError
Raised when attempting to create a resource that already exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message describing the conflict. |
required |
resource_type
|
str | None
|
Optional type of resource. |
None
|
resource_id
|
str | None
|
Optional resource identifier. |
None
|
**kwargs
|
Any
|
Additional context passed to FoundationError. |
{}
|
Examples:
>>> raise AlreadyExistsError("User already registered")
>>> raise AlreadyExistsError("Duplicate key", resource_type="user", resource_id="[email protected]")
Source code in provide/foundation/errors/resources.py
AuthenticationError
¶
AuthenticationError(
message: str,
*,
auth_method: str | None = None,
realm: str | None = None,
**kwargs: Any
)
Bases: FoundationError
Raised when authentication fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message describing the authentication failure. |
required |
auth_method
|
str | None
|
Optional authentication method used. |
None
|
realm
|
str | None
|
Optional authentication realm. |
None
|
**kwargs
|
Any
|
Additional context passed to FoundationError. |
{}
|
Examples:
>>> raise AuthenticationError("Invalid credentials")
>>> raise AuthenticationError("Token expired", auth_method="jwt")
Source code in provide/foundation/errors/auth.py
AuthorizationError
¶
AuthorizationError(
message: str,
*,
required_permission: str | None = None,
resource: str | None = None,
actor: str | None = None,
**kwargs: Any
)
Bases: FoundationError
Raised when authorization fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message describing the authorization failure. |
required |
required_permission
|
str | None
|
Optional required permission. |
None
|
resource
|
str | None
|
Optional resource being accessed. |
None
|
actor
|
str | None
|
Optional actor (user/service) attempting access. |
None
|
**kwargs
|
Any
|
Additional context passed to FoundationError. |
{}
|
Examples:
>>> raise AuthorizationError("Access denied")
>>> raise AuthorizationError("Insufficient permissions", required_permission="admin")
Source code in provide/foundation/errors/auth.py
CommandNotFoundError
¶
CommandNotFoundError(
message: str,
*,
command: str | list[str] | None = None,
return_code: int | None = None,
stdout: str | bytes | None = None,
stderr: str | bytes | None = None,
timeout: bool = False,
code: str | None = None,
**extra_context: Any
)
Bases: ProcessError
Error when a command/executable is not found.
Source code in provide/foundation/errors/process.py
ConcurrencyError
¶
ConcurrencyError(
message: str,
*,
conflict_type: str | None = None,
version_expected: Any = None,
version_actual: Any = None,
**kwargs: Any
)
Bases: FoundationError
Raised when concurrency conflicts occur.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message describing the concurrency issue. |
required |
conflict_type
|
str | None
|
Optional type of conflict (lock, version, etc.). |
None
|
version_expected
|
Any
|
Optional expected version. |
None
|
version_actual
|
Any
|
Optional actual version. |
None
|
**kwargs
|
Any
|
Additional context passed to FoundationError. |
{}
|
Examples:
>>> raise ConcurrencyError("Optimistic lock failure")
>>> raise ConcurrencyError("Version mismatch", version_expected=1, version_actual=2)
Source code in provide/foundation/errors/runtime.py
ConfigValidationError
¶
Bases: ValidationError
Raised when configuration validation fails.
This is a specialized validation error for configuration-specific validation failures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Validation error message. |
required |
config_class
|
str | None
|
Optional name of the config class. |
None
|
**kwargs
|
Any
|
Additional context passed to ValidationError. |
{}
|
Examples:
>>> raise ConfigValidationError("Invalid database configuration")
>>> raise ConfigValidationError("Port must be positive", field="port", value=-1)
Source code in provide/foundation/errors/config.py
ConfigurationError
¶
ConfigurationError(
message: str,
*,
config_key: str | None = None,
config_source: str | None = None,
**kwargs: Any
)
Bases: FoundationError
Raised when configuration is invalid or cannot be loaded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message describing the configuration issue. |
required |
config_key
|
str | None
|
Optional configuration key that caused the error. |
None
|
config_source
|
str | None
|
Optional source of the configuration (file, env, etc.). |
None
|
**kwargs
|
Any
|
Additional context passed to FoundationError. |
{}
|
Examples:
>>> raise ConfigurationError("Missing required config")
>>> raise ConfigurationError("Invalid timeout", config_key="timeout")
Source code in provide/foundation/errors/config.py
DependencyError
¶
DependencyError(
package: str,
*,
feature: str | None = None,
install_command: str | None = None,
**kwargs: Any
)
Bases: FoundationError
Raised when an optional dependency is required but not installed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package
|
str
|
Name of the missing package |
required |
feature
|
str | None
|
Optional feature name that requires the package |
None
|
install_command
|
str | None
|
Optional custom installation command |
None
|
**kwargs
|
Any
|
Additional context passed to FoundationError |
{}
|
Examples:
>>> raise DependencyError("cryptography", feature="crypto")
>>> raise DependencyError("requests", install_command="pip install requests")
Source code in provide/foundation/errors/dependencies.py
DependencyMismatchError
¶
DependencyMismatchError(
package: str,
*,
required_version: str,
current_version: str,
**kwargs: Any
)
Bases: FoundationError
Raised when a dependency version doesn't meet requirements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package
|
str
|
Name of the package with version mismatch |
required |
required_version
|
str
|
Required version or constraint |
required |
current_version
|
str
|
Currently installed version |
required |
**kwargs
|
Any
|
Additional context passed to FoundationError |
{}
|
Examples:
Source code in provide/foundation/errors/dependencies.py
ErrorCode
¶
Standard error codes for programmatic error handling.
Use these codes for consistent error identification across the system. Codes are grouped by category with prefixes: - CFG: Configuration errors - VAL: Validation errors - INT: Integration errors - RES: Resource errors - AUTH: Authentication/Authorization errors - SYS: System errors
ErrorContext
¶
Rich error context for diagnostics and monitoring.
Provides a flexible container for error metadata that can be used by different systems (logging, monitoring, Terraform, etc.).
Attributes:
| Name | Type | Description |
|---|---|---|
timestamp |
datetime
|
When the error occurred. |
severity |
ErrorSeverity
|
Error severity level. |
category |
ErrorCategory
|
Error category for classification. |
metadata |
dict[str, dict[str, Any]]
|
Namespace-based metadata storage. |
tags |
set[str]
|
Set of tags for categorization and filtering. |
trace_id |
str | None
|
Optional trace ID for distributed tracing. |
span_id |
str | None
|
Optional span ID for distributed tracing. |
Examples:
>>> ctx = ErrorContext(severity=ErrorSeverity.HIGH)
>>> ctx.add_namespace("aws", {"region": "us-east-1", "account": "123456"})
>>> ctx.add_tag("production")
Functions¶
add_namespace
¶
Add namespaced metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str
|
Namespace key (e.g., 'terraform', 'aws', 'http'). |
required |
data
|
dict[str, Any]
|
Metadata for this namespace. |
required |
Returns:
| Type | Description |
|---|---|
ErrorContext
|
Self for method chaining. |
Examples:
>>> ctx.add_namespace("terraform", {"provider": "aws", "version": "5.0"})
>>> ctx.add_namespace("http", {"method": POST, "status": 500})
Source code in provide/foundation/errors/context.py
add_tag
¶
Add a tag for categorization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tag
|
str
|
Tag to add. |
required |
Returns:
| Type | Description |
|---|---|
ErrorContext
|
Self for method chaining. |
add_tags
¶
Add multiple tags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*tags
|
str
|
Tags to add. |
()
|
Returns:
| Type | Description |
|---|---|
ErrorContext
|
Self for method chaining. |
get_namespace
¶
to_dict
¶
Convert to dictionary for logging and serialization.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Flattened dictionary with namespaced keys. |
Examples:
Source code in provide/foundation/errors/context.py
to_logging_context
¶
to_terraform_diagnostic
¶
Convert to Terraform diagnostic format.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary formatted for Terraform diagnostics. |
Examples:
Source code in provide/foundation/errors/context.py
update_namespace
¶
Update existing namespace metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str
|
Namespace key to update. |
required |
data
|
dict[str, Any]
|
Metadata to merge into namespace. |
required |
Returns:
| Type | Description |
|---|---|
ErrorContext
|
Self for method chaining. |
Source code in provide/foundation/errors/context.py
ErrorHandler
¶
Configurable error handler with type-based policies.
Attributes:
| Name | Type | Description |
|---|---|---|
policies |
dict[type[Exception], Callable[[Exception], Any]]
|
Mapping of error types to handler functions. |
default_action |
Callable[[Exception], Any]
|
Default handler for unmatched errors. |
log_all |
bool
|
Whether to log all handled errors. |
capture_context |
bool
|
Whether to capture error context. |
reraise_unhandled |
bool
|
Whether to re-raise unhandled errors. |
Examples:
>>> def handle_validation(e: ValidationError):
... return {"error": "Invalid input", "details": e.context}
...
>>> handler = ErrorHandler(
... policies={ValidationError: handle_validation},
... default_action=lambda e: None
... )
>>> result = handler.handle(some_error)
Functions¶
add_policy
¶
Add or update a handler policy for an error type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error_type
|
type[Exception]
|
Exception type to handle. |
required |
handler
|
Callable[[Exception], Any]
|
Handler function for this error type. |
required |
Returns:
| Type | Description |
|---|---|
ErrorHandler
|
Self for method chaining. |
Source code in provide/foundation/errors/handlers.py
handle
¶
Handle an error based on configured policies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error
|
Exception
|
The exception to handle. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Result from the handler function. |
Raises:
| Type | Description |
|---|---|
Exception
|
The original error if reraise_unhandled=True and no handler matches. |
Examples:
Source code in provide/foundation/errors/handlers.py
ErrorMetadata
¶
Additional metadata for error tracking and debugging.
Attributes:
| Name | Type | Description |
|---|---|---|
request_id |
str | None
|
Optional request identifier for tracing. |
user_id |
str | None
|
Optional user identifier. |
session_id |
str | None
|
Optional session identifier. |
correlation_id |
str | None
|
Optional correlation ID for distributed tracing. |
retry_count |
int
|
Number of retry attempts made. |
retry_after |
float | None
|
Seconds to wait before retry. |
help_url |
str | None
|
Optional URL for more information. |
support_id |
str | None
|
Optional support ticket/case ID. |
Examples:
Functions¶
to_dict
¶
Convert to dictionary, excluding None values.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with non-None metadata fields. |
Source code in provide/foundation/errors/types.py
FoundationError
¶
FoundationError(
message: str,
*,
code: str | None = None,
context: dict[str, Any] | None = None,
cause: Exception | None = None,
**extra_context: Any
)
Bases: Exception
Base exception for all Foundation errors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Human-readable error message. |
required |
code
|
str | None
|
Optional error code for programmatic handling. |
None
|
context
|
dict[str, Any] | None
|
Optional context dictionary with diagnostic data. |
None
|
cause
|
Exception | None
|
Optional underlying exception that caused this error. |
None
|
**extra_context
|
Any
|
Additional key-value pairs added to context. |
{}
|
Examples:
>>> raise FoundationError("Operation failed")
>>> raise FoundationError("Operation failed", code="OP_001")
>>> raise FoundationError("Operation failed", user_id=123, retry_count=3)
Source code in provide/foundation/errors/base.py
Functions¶
add_context
¶
Add context data to the error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Context key (use dots for namespacing, e.g., 'aws.region'). |
required |
value
|
Any
|
Context value. |
required |
Returns:
| Type | Description |
|---|---|
FoundationError
|
Self for method chaining. |
Source code in provide/foundation/errors/base.py
to_dict
¶
Convert exception to dictionary for structured logging.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary representation suitable for logging/serialization. |
Source code in provide/foundation/errors/base.py
IntegrationError
¶
IntegrationError(
message: str,
*,
service: str | None = None,
endpoint: str | None = None,
status_code: int | None = None,
**kwargs: Any
)
Bases: FoundationError
Raised when external service integration fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message describing the integration failure. |
required |
service
|
str | None
|
Optional service name that failed. |
None
|
endpoint
|
str | None
|
Optional endpoint that was called. |
None
|
status_code
|
int | None
|
Optional HTTP status code. |
None
|
**kwargs
|
Any
|
Additional context passed to FoundationError. |
{}
|
Examples:
>>> raise IntegrationError("API call failed")
>>> raise IntegrationError("Auth failed", service="github", status_code=401)
Source code in provide/foundation/errors/integration.py
NetworkError
¶
Bases: IntegrationError
Raised for network-related failures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message describing the network issue. |
required |
host
|
str | None
|
Optional hostname or IP address. |
None
|
port
|
int | None
|
Optional port number. |
None
|
**kwargs
|
Any
|
Additional context passed to IntegrationError. |
{}
|
Examples:
>>> raise NetworkError("Connection refused")
>>> raise NetworkError("DNS resolution failed", host="api.example.com")
Source code in provide/foundation/errors/integration.py
NotFoundError
¶
NotFoundError(
message: str,
*,
resource_type: str | None = None,
resource_id: str | None = None,
**kwargs: Any
)
Bases: FoundationError
Raised when a requested resource cannot be found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message describing what was not found. |
required |
resource_type
|
str | None
|
Optional type of resource. |
None
|
resource_id
|
str | None
|
Optional resource identifier. |
None
|
**kwargs
|
Any
|
Additional context passed to FoundationError. |
{}
|
Examples:
>>> raise NotFoundError("User not found")
>>> raise NotFoundError("Entity missing", resource_type="user", resource_id="123")
Source code in provide/foundation/errors/resources.py
ProcessError
¶
ProcessError(
message: str,
*,
command: str | list[str] | None = None,
return_code: int | None = None,
stdout: str | bytes | None = None,
stderr: str | bytes | None = None,
timeout: bool = False,
code: str | None = None,
**extra_context: Any
)
Bases: FoundationError
Error for external process execution failures with output capture.
Initialize ProcessError with command execution details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Human-readable error message |
required |
command
|
str | list[str] | None
|
The command that was executed |
None
|
return_code
|
int | None
|
Process return/exit code |
None
|
stdout
|
str | bytes | None
|
Standard output from the process |
None
|
stderr
|
str | bytes | None
|
Standard error from the process |
None
|
timeout
|
bool
|
Whether the process timed out |
False
|
code
|
str | None
|
Optional error code |
None
|
**extra_context
|
Any
|
Additional context information |
{}
|
Source code in provide/foundation/errors/process.py
Functions¶
ProcessTimeoutError
¶
ProcessTimeoutError(
message: str,
*,
command: str | list[str] | None = None,
timeout_seconds: float | None = None,
stdout: str | bytes | None = None,
stderr: str | bytes | None = None,
code: str | None = None,
**extra_context: Any
)
Bases: ProcessError
Error when a process times out.
Source code in provide/foundation/errors/process.py
RateLimitExceededError
¶
RateLimitExceededError(
message: str,
*,
limit: float | None = None,
retry_after: float | None = None,
current_rate: float | None = None,
**kwargs: Any
)
Bases: FoundationError
Raised when a rate limit is exceeded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message describing the rate limit violation. |
required |
limit
|
float | None
|
The rate limit that was exceeded (requests/messages per time unit). |
None
|
retry_after
|
float | None
|
Seconds to wait before retrying. |
None
|
current_rate
|
float | None
|
Optional current rate at time of error. |
None
|
**kwargs
|
Any
|
Additional context passed to FoundationError. |
{}
|
Examples:
>>> raise RateLimitExceededError("Log rate limit exceeded", limit=100.0, retry_after=1.0)
>>> raise RateLimitExceededError("API rate limit", limit=1000, retry_after=60, current_rate=1050)
Source code in provide/foundation/errors/runtime.py
ResourceError
¶
ResourceError(
message: str,
*,
resource_type: str | None = None,
resource_path: str | None = None,
**kwargs: Any
)
Bases: FoundationError
Raised when resource operations fail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message describing the resource issue. |
required |
resource_type
|
str | None
|
Optional type of resource (file, network, etc.). |
None
|
resource_path
|
str | None
|
Optional path or identifier of the resource. |
None
|
**kwargs
|
Any
|
Additional context passed to FoundationError. |
{}
|
Examples:
>>> raise ResourceError("File not found")
>>> raise ResourceError("Permission denied", resource_type="file", resource_path="/etc/config")
Source code in provide/foundation/errors/resources.py
RuntimeError
¶
RuntimeError(
message: str,
*,
operation: str | None = None,
retry_possible: bool = False,
**kwargs: Any
)
Bases: FoundationError
Raised for runtime operational errors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message describing the runtime issue. |
required |
operation
|
str | None
|
Optional operation that failed. |
None
|
retry_possible
|
bool
|
Whether the operation can be retried. |
False
|
**kwargs
|
Any
|
Additional context passed to FoundationError. |
{}
|
Examples:
>>> raise RuntimeError("Process failed")
>>> raise RuntimeError("Lock timeout", operation="acquire_lock", retry_possible=True)
Source code in provide/foundation/errors/runtime.py
StateError
¶
StateError(
message: str,
*,
current_state: str | None = None,
expected_state: str | None = None,
transition: str | None = None,
**kwargs: Any
)
Bases: FoundationError
Raised when an operation is invalid for the current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message describing the state issue. |
required |
current_state
|
str | None
|
Optional current state. |
None
|
expected_state
|
str | None
|
Optional expected state. |
None
|
transition
|
str | None
|
Optional attempted transition. |
None
|
**kwargs
|
Any
|
Additional context passed to FoundationError. |
{}
|
Examples:
>>> raise StateError("Invalid state transition")
>>> raise StateError("Not ready", current_state="initializing", expected_state="ready")
Source code in provide/foundation/errors/runtime.py
TimeoutError
¶
TimeoutError(
message: str,
*,
timeout_seconds: float | None = None,
elapsed_seconds: float | None = None,
**kwargs: Any
)
Bases: IntegrationError
Raised when operations exceed time limits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Error message describing the timeout. |
required |
timeout_seconds
|
float | None
|
Optional timeout limit in seconds. |
None
|
elapsed_seconds
|
float | None
|
Optional actual elapsed time. |
None
|
**kwargs
|
Any
|
Additional context passed to IntegrationError. |
{}
|
Examples:
>>> raise TimeoutError("Request timed out")
>>> raise TimeoutError("Operation exceeded limit", timeout_seconds=30, elapsed_seconds=31.5)
Source code in provide/foundation/errors/integration.py
ValidationError
¶
ValidationError(
message: str,
*,
field: str | None = None,
value: Any = None,
rule: str | None = None,
**kwargs: Any
)
Bases: FoundationError
Raised when data validation fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Validation error message. |
required |
field
|
str | None
|
Optional field name that failed validation. |
None
|
value
|
Any
|
Optional invalid value. |
None
|
rule
|
str | None
|
Optional validation rule that failed. |
None
|
**kwargs
|
Any
|
Additional context passed to FoundationError. |
{}
|
Examples:
>>> raise ValidationError("Invalid email format")
>>> raise ValidationError("Value out of range", field="age", value=-1)
Source code in provide/foundation/errors/config.py
Functions¶
capture_error_context
¶
capture_error_context(
error: Exception,
severity: ErrorSeverity | None = None,
category: ErrorCategory | None = None,
**namespaces: dict[str, Any]
) -> ErrorContext
Capture error context from an exception.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error
|
Exception
|
Exception to capture context from. |
required |
severity
|
ErrorSeverity | None
|
Optional severity override. |
None
|
category
|
ErrorCategory | None
|
Optional category override. |
None
|
**namespaces
|
dict[str, Any]
|
Namespace data to add to context. |
{}
|
Returns:
| Type | Description |
|---|---|
ErrorContext
|
ErrorContext with captured information. |
Examples:
>>> try:
... risky_operation()
... except Exception as e:
... ctx = capture_error_context(
... e,
... severity=ErrorSeverity.HIGH,
... aws={"region": "us-east-1"},
... http={"status": 500}
... )
Source code in provide/foundation/errors/context.py
error_boundary
¶
error_boundary(
*catch: type[Exception],
on_error: Callable[[Exception], Any] | None = None,
log_errors: bool = True,
reraise: bool = True,
context: dict[str, Any] | None = None,
fallback: Any = None
) -> Generator[None, None, None]
Context manager for structured error handling with logging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*catch
|
type[Exception]
|
Exception types to catch (defaults to Exception if empty). |
()
|
on_error
|
Callable[[Exception], Any] | None
|
Optional callback function when error is caught. |
None
|
log_errors
|
bool
|
Whether to log caught errors. |
True
|
reraise
|
bool
|
Whether to re-raise after handling. |
True
|
context
|
dict[str, Any] | None
|
Additional context for error logging. |
None
|
fallback
|
Any
|
Value to return if error is suppressed (when reraise=False). |
None
|
Yields:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> # Suppress and log specific errors
>>> with error_boundary(KeyError, reraise=False, fallback=None):
... value = data["missing_key"]
Source code in provide/foundation/errors/handlers.py
fallback_on_error
¶
fallback_on_error(
fallback_func: Callable[..., Any],
*exceptions: type[Exception],
log_errors: bool = True
) -> Callable[[F], F]
Decorator to call a fallback function when errors occur.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fallback_func
|
Callable[..., Any]
|
Function to call when an error occurs. |
required |
*exceptions
|
type[Exception]
|
Specific exception types to handle (all if empty). |
()
|
log_errors
|
bool
|
Whether to log errors before calling fallback. |
True
|
Returns:
| Type | Description |
|---|---|
Callable[[F], F]
|
Decorated function. |
Examples:
>>> def use_cache():
... return cached_value
...
>>> @fallback_on_error(use_cache, NetworkError)
... def fetch_from_api():
... return api_call()
Source code in provide/foundation/errors/decorators.py
handle_error
¶
handle_error(
error: Exception,
*,
log: bool = True,
capture_context: bool = True,
reraise: bool = False,
fallback: Any = None
) -> Any
Handle an error with logging and optional context capture.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error
|
Exception
|
The exception to handle. |
required |
log
|
bool
|
Whether to log the error. |
True
|
capture_context
|
bool
|
Whether to capture error context. |
True
|
reraise
|
bool
|
Whether to re-raise the error after handling. |
False
|
fallback
|
Any
|
Value to return if not re-raising. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The fallback value if not re-raising. |
Raises:
| Type | Description |
|---|---|
Exception
|
The original error if reraise=True. |
Examples:
>>> try:
... risky_operation()
... except ValueError as e:
... result = handle_error(e, fallback="default")
Source code in provide/foundation/errors/handlers.py
log_only_error_context
¶
log_only_error_context(
*,
context_provider: (
Callable[[], dict[str, Any]] | None
) = None,
log_level: str = "debug",
log_success: bool = False
) -> Callable[[F], F]
Safe decorator that only adds logging context without changing error behavior.
This decorator preserves the exact original error message and type while adding structured logging context. It never suppresses errors or changes their behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context_provider
|
Callable[[], dict[str, Any]] | None
|
Function that provides additional logging context. |
None
|
log_level
|
str
|
Level for operation logging ('debug', 'trace', etc.) |
'debug'
|
log_success
|
bool
|
Whether to log successful operations. |
False
|
Returns:
| Type | Description |
|---|---|
Callable[[F], F]
|
Decorated function that preserves all original error behavior. |
Examples:
>>> @log_only_error_context(
... context_provider=lambda: {"operation": "detect_launcher_type"},
... log_level="trace"
... )
... def detect_launcher_type(self, path):
... # Original error messages preserved exactly
... return self._internal_detect(path)
Source code in provide/foundation/errors/safe_decorators.py
resilient
¶
resilient(
func: None = None,
*,
fallback: Any = None,
log_errors: bool = True,
context_provider: (
Callable[[], dict[str, Any]] | None
) = None,
context: dict[str, Any] | None = None,
error_mapper: (
Callable[[Exception], Exception] | None
) = None,
suppress: tuple[type[Exception], ...] | None = None,
reraise: bool = True
) -> Callable[[F], F]
resilient(
func: F | None = None,
*,
fallback: Any = None,
log_errors: bool = True,
context_provider: (
Callable[[], dict[str, Any]] | None
) = None,
context: dict[str, Any] | None = None,
error_mapper: (
Callable[[Exception], Exception] | None
) = None,
suppress: tuple[type[Exception], ...] | None = None,
reraise: bool = True
) -> Callable[[F], F] | F
Decorator for automatic error handling with logging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fallback
|
Any
|
Value to return when an error occurs. |
None
|
log_errors
|
bool
|
Whether to log errors. |
True
|
context_provider
|
Callable[[], dict[str, Any]] | None
|
Function that provides additional logging context. |
None
|
context
|
dict[str, Any] | None
|
Static context dict to include in logs (alternative to context_provider). |
None
|
error_mapper
|
Callable[[Exception], Exception] | None
|
Function to transform exceptions before re-raising. |
None
|
suppress
|
tuple[type[Exception], ...] | None
|
Tuple of exception types to suppress (return fallback instead). |
None
|
reraise
|
bool
|
Whether to re-raise exceptions after logging (default: True). |
True
|
Returns:
| Type | Description |
|---|---|
Callable[[F], F] | F
|
Decorated function. |
Note
Preserving Context in error_mapper: When using error_mapper with FoundationError exceptions, the original exception's context dictionary is not automatically transferred to the mapped exception. To preserve rich context, manually copy it:
from provide.foundation.errors import FoundationError @resilient( ... error_mapper=lambda e: ( ... ValidationError( ... str(e), ... context=e.context if isinstance(e, FoundationError) else {} ... ) if isinstance(e, FoundationError) ... else DomainError(str(e)) ... ) ... ) ... def process_data(data): ... # Low-level FoundationError will be mapped to ValidationError ... # with context preserved ... pass
Examples:
>>> @resilient(fallback=None, suppress=(KeyError,))
... def get_value(data, key):
... return data[key]
>>> @resilient(
... context_provider=lambda: {"request_id": get_request_id()}
... )
... def process_request():
... # errors will be logged with request_id
... pass
>>> @resilient(
... reraise=False,
... context={"component": "orchestrator", "method": "run"}
... )
... def run():
... # errors will be logged but not re-raised
... pass
Source code in provide/foundation/errors/decorators.py
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | |
suppress_and_log
¶
suppress_and_log(
*exceptions: type[Exception],
fallback: Any = None,
log_level: str = "warning"
) -> Callable[[F], F]
Decorator to suppress specific exceptions and log them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*exceptions
|
type[Exception]
|
Exception types to suppress. |
()
|
fallback
|
Any
|
Value to return when exception is suppressed. |
None
|
log_level
|
str
|
Log level to use ('debug', 'info', 'warning', 'error'). |
'warning'
|
Returns:
| Type | Description |
|---|---|
Callable[[F], F]
|
Decorated function. |
Examples:
>>> @suppress_and_log(KeyError, AttributeError, fallback={})
... def get_nested_value(data):
... return data["key"].attribute
Source code in provide/foundation/errors/decorators.py
transactional
¶
transactional(
rollback: Callable[[], None],
commit: Callable[[], None] | None = None,
on_error: Callable[[Exception], None] | None = None,
log_errors: bool = True,
) -> Generator[None, None, None]
Context manager for transactional operations with rollback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rollback
|
Callable[[], None]
|
Function to call on error to rollback changes. |
required |
commit
|
Callable[[], None] | None
|
Optional function to call on success. |
None
|
on_error
|
Callable[[Exception], None] | None
|
Optional error handler before rollback. |
None
|
log_errors
|
bool
|
Whether to log errors. |
True
|
Yields:
| Type | Description |
|---|---|
None
|
None |
Examples:
>>> def rollback_changes():
... db.rollback()
...
>>> def commit_changes():
... db.commit()
...
>>> with transactional(rollback_changes, commit_changes):
... db.execute("INSERT INTO users ...")
... db.execute("UPDATE accounts ...")