-
-
Save datavudeja/553a634a7c89ed194252189c99b5b594 to your computer and use it in GitHub Desktop.
A python function decorator to catch exceptions and report their contents
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, Any | |
| import functools | |
| import traceback | |
| def handle_exceptions(func: Callable[..., Any]) -> Callable[..., Any]: | |
| """ | |
| Decorate a function to catch and handle exceptions by returning a detailed error message. | |
| Args: | |
| func (Callable[..., Any]): The function to be decorated. | |
| Returns: | |
| Callable[..., Any]: A wrapped function that handles exceptions and returns a structured error message. | |
| The returned dictionary contains: | |
| - 'message': A generic error message. | |
| - 'data': A dictionary with detailed information about the exception: | |
| - 'title': The type of the exception. | |
| - 'message': The exception message. | |
| - 'traceback': A list of formatted traceback lines. | |
| """ | |
| @functools.wraps(func) | |
| def wrapper(*args: Any, **kwargs: Any) -> Any: | |
| try: | |
| return func(*args, **kwargs) | |
| except Exception as exc: # noqa: BLE001 | |
| tb = traceback.TracebackException.from_exception( | |
| exc, | |
| capture_locals=False, | |
| ) | |
| return { | |
| "message": "An unhandled exception occurred.", | |
| "data": { | |
| "title": type(exc).__name__, | |
| "message": str(exc), | |
| "traceback": [ | |
| line | |
| for part in tb.format() | |
| for line in part.split("\n") | |
| if line.strip() | |
| ], | |
| }, | |
| } | |
| return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment