Last active
August 10, 2020 17:42
-
-
Save Eduard-gan/f769c239d0b4021d55f9b065bebbba11 to your computer and use it in GitHub Desktop.
Python: Exception class that brings some structured data to caller
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
import logging | |
class InsufficientFunds(PaymentSystemError): | |
requested_amount: float = None | |
direction: FinDirection = None | |
account_balance: float = None | |
def __init__(self, *args, direction=None, requested_amount=None, account_balance=None, **kwargs): | |
self.direction = direction | |
self.account_balance = account_balance | |
self.requested_amount = requested_amount | |
super().__init__(*args) | |
def __repr__(self): | |
text = f"{self.__class__.__name__}(" | |
if self.args: | |
text += f"{', '.join(repr(x) if not isinstance(x, Enum) else str(x) for x in self.args)}" | |
text += ", " | |
for kw in ("direction", "account_balance", "requested_amount"): | |
value = getattr(self, kw) | |
text += f"{kw}={repr(value) if not isinstance(value, Enum) else str(value)}, " | |
return text[:-2] + ")" | |
try: | |
try: | |
raise InsufficientFunds("Buggy code here", requested_amount=-1) | |
except InsufficientFunds as e: | |
if e.requested_amount < 0: | |
print(f"A bug is somewhere deep inside of a call chain: requested amount {e.requested_amount} is less than zero!") | |
raise | |
else: | |
print("Do something, log something, based on exception and its context data") | |
raise | |
except Exception as e: | |
print(repr(e)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment