Created
July 26, 2024 13:55
-
-
Save rpdelaney/a08fd2e772727bb5cc2a0b69e6dfa202 to your computer and use it in GitHub Desktop.
A python function decorator to catch exceptions and report their contents
This file contains 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