Skip to content

wg_utilities.exceptions

Custom exception types.

BadDefinitionError

Bases: WGUtilitiesError

Raised when some kind of definition is invalid.

Source code in wg_utilities/exceptions/_exception.py
19
20
class BadDefinitionError(WGUtilitiesError):
    """Raised when some kind of definition is invalid."""

BadUsageError

Bases: WGUtilitiesError

Raised when something is used incorrectly.

Source code in wg_utilities/exceptions/_exception.py
23
24
class BadUsageError(WGUtilitiesError):
    """Raised when something is used incorrectly."""

NotFoundError

Bases: WGUtilitiesError

Raised when something is not found.

Source code in wg_utilities/exceptions/_exception.py
27
28
class NotFoundError(WGUtilitiesError):
    """Raised when something is not found."""

WGUtilitiesError

Bases: Exception

Base class for all exceptions raised by wg_utilities.

Source code in wg_utilities/exceptions/_exception.py
 9
10
11
12
13
14
15
16
class WGUtilitiesError(Exception):
    """Base class for all exceptions raised by wg_utilities."""

    @classmethod
    @lru_cache
    def subclasses(cls) -> list[type[Self]]:
        """Return a list of all subclasses of this error, cached for performance."""
        return list(subclasses_recursive(cls))

subclasses() cached classmethod

Return a list of all subclasses of this error, cached for performance.

Source code in wg_utilities/exceptions/_exception.py
12
13
14
15
16
@classmethod
@lru_cache
def subclasses(cls) -> list[type[Self]]:
    """Return a list of all subclasses of this error, cached for performance."""
    return list(subclasses_recursive(cls))

on_exception(exception_callback=send_exception_to_home_assistant, *, raise_after_callback=True, logger=None, ignore_exception_types=None, default_return_value=None, _suppress_ignorant_warnings=None)

Allow simple cover-all exception handler callback behaviour.

Parameters:

Name Type Description Default
exception_callback Callable

callback function to process the exception

send_exception_to_home_assistant
raise_after_callback bool

raise the exception after the callback has run

True
logger Logger

optional logger for logging the exception

None
ignore_exception_types Iterable[type[Exception]]

optional iterable of exception types to ignore

None
default_return_value Any

optional default return value for the decorated function

None
_suppress_ignorant_warnings bool

optional flag to suppress warnings about ignoring exception types

None

Returns:

Name Type Description
Callable Callable[[Any], Any]

the actual decorator

Source code in wg_utilities/exceptions/_deprecated.py
 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
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def on_exception(
    exception_callback: Callable[[Exception], Any] = send_exception_to_home_assistant,
    *,
    raise_after_callback: bool = True,
    logger: Logger | None = None,
    ignore_exception_types: Iterable[type[Exception]] | None = None,
    default_return_value: Any | None = None,
    _suppress_ignorant_warnings: bool | None = None,
) -> Callable[[Any], Any]:
    """Allow simple cover-all exception handler callback behaviour.

    Args:
        exception_callback (Callable): callback function to process the exception
        raise_after_callback (bool): raise the exception after the callback has run
        logger (Logger): optional logger for logging the exception
        ignore_exception_types (Iterable[type[Exception]]): optional iterable of
            exception types to ignore
        default_return_value (Any): optional default return value for the decorated
            function
        _suppress_ignorant_warnings (bool): optional flag to suppress warnings about
            ignoring exception types

    Returns:
        Callable: the actual decorator
    """

    if default_return_value is not None and raise_after_callback:
        raise ValueError(
            "The `default_return_value` parameter can only be set when"
            " `raise_after_callback` is False.",
        )

    def _decorator(func: Callable[[Any], Any]) -> Callable[[Any, Any], Any]:
        """Allow simple cover-all exception handler callback behaviour.

        Args:
            func (Callable): the function being wrapped

        Returns:
            Callable: the inner function
        """

        @wraps(func)
        def worker(*args: Any, **kwargs: Any) -> Any:
            """Try to run the decorated function and calls the callback function.

            Args:
                *args (Any): any args passed to the inner func
                **kwargs (Any): any kwargs passed to the inner func

            Returns:
                Any: the result of the wrapped function

            Raises:
                Exception: any exception from the decorated function
            """
            global LOGGER

            try:
                return func(*args, **kwargs)
            except Exception as exc:
                if ignore_exception_types and any(
                    isinstance(exc, exc_type) for exc_type in ignore_exception_types
                ):
                    if (
                        getenv("SUPPRESS_WG_UTILS_IGNORANCE") != "1"
                        and _suppress_ignorant_warnings is None
                    ) or _suppress_ignorant_warnings is False:
                        (
                            logger
                            or LOGGER
                            or (LOGGER := add_stream_handler(getLogger(__name__)))
                        ).warning(
                            "Ignoring exception of type %s in %s.%s. This function has"
                            " ceased executing at line %i. To suppress these warnings"
                            " set the `_suppress_ignorant_warnings` parameter to True"
                            ' or env var `SUPPRESS_WG_UTILS_IGNORANCE` to "1".',
                            type(exc).__name__,
                            func.__module__,
                            func.__name__,
                            exc_info()[2].tb_lineno,  # type: ignore[union-attr]
                        )
                else:
                    exception_callback(exc)

                    if raise_after_callback:
                        raise

                return default_return_value

        return worker

    return _decorator

send_exception_to_home_assistant(exc)

Format an exception and send useful info to Home Assistant.

Parameters:

Name Type Description Default
exc Exception

the exception being handled

required

Raises:

Type Description
ValueError

if the HA_LOG_ENDPOINT isn't set

Exception

if posting the exception to HA fails, then an exception is raised

Source code in wg_utilities/exceptions/_deprecated.py
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
def send_exception_to_home_assistant(exc: Exception) -> None:
    """Format an exception and send useful info to Home Assistant.

    Args:
        exc (Exception): the exception being handled

    Raises:
        ValueError: if the HA_LOG_ENDPOINT isn't set
        Exception: if posting the exception to HA fails, then an exception is raised
    """
    payload = {
        "client": gethostname(),
        "message": f"{type(exc).__name__} in `{stack()[2].filename}`: {exc!r}",
        "traceback": format_exc(),
    }

    try:
        try:
            # If the host is on the same network as HA, then an HTTP local URL can be
            # used
            res = post(f"http://{HA_LOG_ENDPOINT}/log/error", json=payload, timeout=10)
        except RequestsConnectionError as ha_exc:
            if "Failed to establish a new connection" not in str(ha_exc):
                raise

            res = post(f"https://{HA_LOG_ENDPOINT}/log/error", json=payload, timeout=10)

        res.raise_for_status()
    except Exception as send_exc:
        raise send_exc from exc