Created
April 17, 2024 11:25
-
-
Save eugen-hoppe/c20688d17c7682cf1284718a655d0e0d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from typing import Callable, Tuple, Type, Optional | |
| from functools import wraps | |
| def try_except( | |
| errors: Tuple[Type[Exception], ...] = (Exception,), | |
| raise_: Optional[Type[Exception]] = None, | |
| txt_: str = "" | |
| ) -> Callable: | |
| """A decorator that wraps a function to handle exceptions""" | |
| def decorator(func: Callable) -> Callable: | |
| @wraps(func) | |
| def wrapper(*args: any, **kwargs: any) -> any: | |
| try: | |
| return func(*args, **kwargs) | |
| except errors as err: | |
| if raise_ is not None: | |
| from_error = err if "#debug" in txt_ else None | |
| msg_ = txt_ + " (INFO: add '#debug' for traceback chain)" | |
| raise raise_(msg_) from from_error | |
| raise err | |
| return wrapper | |
| return decorator | |
| if __name__ == "__main__": | |
| # Example | |
| # ======= | |
| @try_except((ZeroDivisionError,), ValueError, "Division by Zero #debug") | |
| def divide(x: float, y: float) -> float: | |
| return x / y | |
| divide(1, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment