pferd/PFERD/errors.py

37 lines
865 B
Python
Raw Normal View History

"""
An error logging decorator.
"""
import logging
from typing import Any, Callable
2020-05-08 23:47:05 +02:00
from rich.console import Console
2020-05-09 00:00:21 +02:00
from .logging import PrettyLogger
LOGGER = logging.getLogger(__name__)
PRETTY = PrettyLogger(LOGGER)
2020-05-09 00:00:21 +02:00
class FatalException(Exception):
"""
A fatal exception occurred. Recovery is not possible.
"""
def swallow_and_print_errors(function: Callable) -> Callable:
"""
Decorates a function, swallows all errors, logs them and returns none if one occurred.
"""
def inner(*args: Any, **kwargs: Any) -> Any:
# pylint: disable=broad-except
try:
return function(*args, **kwargs)
except FatalException as error:
PRETTY.error(str(error))
return None
except Exception as error:
Console().print_exception()
return None
return inner