File size: 2,837 Bytes
95e1515
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""
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