Python raise_or_log function
Neat snippet I just wrote that will get rid of a lot of duplicated code:
def exception_or_error(
message: str,
fail_loudly: Optional[bool] = False,
exception_type: Optional[Type[Exception]] = ValueError,
) -> None:
"""Log error or raise an exception. Needed to control the decider
in production."""
# Raise whatever exception
if fail_loudly:
raise exception_type(message)
else:
logger.error(message)
Usage:
are_we_in_production = True
# will log or raise a ValueError based on the above
exception_or_error("File not found", fail_loudly=are_we_in_production)
# if raising something, will raise a KeyError
exception_or_error("Row not in db", fail_loudly=are_we_in_production,
exception_type = KeyError)
Nel mezzo del deserto posso dire tutto quello che voglio.
comments powered by Disqus