Last active
November 28, 2024 15:48
-
-
Save PavlosMelissinos/d95e26eabbeb38a10e577a874e0cd6b9 to your computer and use it in GitHub Desktop.
ExceptionInfo is a custom Python exception inspired by Clojure's ExceptionInfo class
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 types import MappingProxyType | |
class ExceptionInfo(Exception): | |
def __init__(self, | |
msg: str = None, | |
data: dict = None, | |
cause: Optional[BaseException] = None): | |
self._message = msg or "" | |
self._data = data or {} | |
self._cause = cause | |
@property | |
def message(self): | |
return self._message | |
@property | |
def data(self): | |
return MappingProxyType(self._data) # Immutable view | |
@property | |
def cause(self): | |
return self._cause | |
def __str__(self): | |
return f"ExceptionInfo: {self._message}" | |
def __repr__(self): | |
return f"ExceptionInfo(msg={self.message}, data={self.data}, cause={self.cause})" | |
def ex_message(e, chain: bool = False, chain_separator: str = " --- "): | |
def ex_message_chain(e): | |
error_message = ex_message(e) | |
next_ex = e.__cause__ or e.__context__ | |
while next_ex: | |
error_message = error_message + chain_separator + ex_message(next_ex) | |
next_ex = next_ex.__cause__ or next_ex.__context__ | |
return error_message | |
try: | |
return ex_message_chain(e) if chain else e.message | |
except AttributeError: | |
return str(e) | |
def ex_data(e) -> dict: | |
try: | |
return e.data | |
except AttributeError: | |
return {} | |
def ex_cause(e): | |
try: | |
return e.cause | |
except AttributeError: | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment