voice-tools / src /models /error_report.py
jcudit's picture
jcudit HF Staff
feat: implement cross-mode robustness fixes (phases 1-8)
95e1515
Raw History Blame Contribute Delete
2.84 kB
"""
Error Report Model
Provides structured error reporting with type categorization for consistent
error handling across web and CLI interfaces.
"""
from typing import Set, TypedDict
class ErrorReport(TypedDict):
"""
Structured error report for all failure scenarios.
Fields:
status: Always "failed" for errors
error: Human-readable error message for end users
error_type: Category of error (audio_io, processing, validation, ssl, model_loading)
"""
status: str
error: str
error_type: str
# Valid error type categories
VALID_ERROR_TYPES: Set[str] = {
"audio_io", # File read/write failures, format issues
"processing", # Algorithm failures, computation errors
"validation", # Invalid parameters, constraint violations
"ssl", # Certificate verification failures, network issues
"model_loading", # HuggingFace Hub errors, missing model files
}
def validate_error_report(report: dict) -> ErrorReport:
"""
Validate error report structure and content.
Args:
report: Dictionary to validate
Returns:
Type-narrowed ErrorReport
Raises:
ValueError: If report is invalid
"""
# Check required keys
required_keys = {"status", "error", "error_type"}
missing = required_keys - report.keys()
if missing:
raise ValueError(f"Missing required keys: {missing}")
# Validate status
if report["status"] != "failed":
raise ValueError(f"Error report status must be 'failed', got '{report['status']}'")
# Validate error message
if not report["error"] or not isinstance(report["error"], str):
raise ValueError("Error message must be non-empty string")
# Validate error_type
if report["error_type"] not in VALID_ERROR_TYPES:
raise ValueError(
f"Invalid error_type: '{report['error_type']}'. Must be one of {VALID_ERROR_TYPES}"
)
return report # Type-narrowed to ErrorReport
def format_error_report(exception: Exception, error_type: str, context: str = "") -> ErrorReport:
"""
Create an ErrorReport from an exception.
Args:
exception: The exception that occurred
error_type: Category of error (must be in VALID_ERROR_TYPES)
context: Optional context to prepend to error message
Returns:
Validated ErrorReport dictionary
Raises:
ValueError: If error_type is invalid
"""
if error_type not in VALID_ERROR_TYPES:
raise ValueError(f"Invalid error_type: '{error_type}'. Must be one of {VALID_ERROR_TYPES}")
# Build error message
error_msg = str(exception)
if context:
error_msg = f"{context}: {error_msg}"
error_report: ErrorReport = {"status": "failed", "error": error_msg, "error_type": error_type}
return error_report