Skip to content

Instantly share code, notes, and snippets.

@e-dreyer
Last active August 8, 2023 18:43
Show Gist options
  • Save e-dreyer/f32519019d4bfaea53dc558423387393 to your computer and use it in GitHub Desktop.
Save e-dreyer/f32519019d4bfaea53dc558423387393 to your computer and use it in GitHub Desktop.
Example of using decorators to wrap functions for exception handling
def handleMastodonExceptions(func) -> Callable:
"""
This is an exception handler that can be used as a wrapper via a decorator to handle Mastodon.py exceptions.
"""
def wrapper(self, *args, **kwargs):
try:
result = func(self, *args, **kwargs)
return result
except MastodonServerError as e:
logging.critical(f"MastodonServerError: {e}")
except MastodonIllegalArgumentError as e:
logging.critical(f"MastodonIllegalArgumentError: {e}")
except MastodonFileNotFoundError as e:
logging.critical(f"MastodonFileNotFoundError: {e}")
except MastodonNetworkError as e:
logging.critical(f"MastodonNetworkError: {e}")
except MastodonAPIError as e:
logging.critical(f"MastodonAPIError: {e}")
except MastodonMalformedEventError as e:
logging.critical(f"MastodonMalformedEventError: {e}")
except MastodonRatelimitError as e:
logging.critical(f"MastodonRatelimitError: {e}")
except MastodonVersionError as e:
logging.critical(f"MastodonVersionError: {e}")
except Exception as e:
logging.critical(f"Error in function {func.__name__}")
logging.critical(e)
raise e
return wrapper
@handleMastodonExceptions
def getAccount(self, account_id: int) -> Dict:
"""
Get information of the account by id
Parameters
----------
account_id: int
ID of the account as per the API
"""
return self._api.account(account_id)
@handleMastodonExceptions
def getMe(self) -> Dict:
"""
Get information of the bot's account
"""
return self._api.me()
@handleMastodonExceptions
def getStatus(self, status_id: int) -> Dict:
"""
Get the status information as per the API
Parameters
----------
status_id: int
The ID of the status as provided by the API
"""
return self._api.status(status_id)
@e-dreyer
Copy link
Author

e-dreyer commented Aug 8, 2023

This is a design pattern I am trying for wrapping classes calling APIs, to keep the exception handling in a single place and not require hundreds of try-except blocks all over the place. It can still be improved by implementing handlers, but for the first version the helped a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment