Skip to content

Instantly share code, notes, and snippets.

@eugen-hoppe
Created April 17, 2024 11:25
Show Gist options
  • Select an option

  • Save eugen-hoppe/c20688d17c7682cf1284718a655d0e0d to your computer and use it in GitHub Desktop.

Select an option

Save eugen-hoppe/c20688d17c7682cf1284718a655d0e0d to your computer and use it in GitHub Desktop.
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