Skip to content

Instantly share code, notes, and snippets.

@dcragusa
Created September 3, 2018 15:48
Show Gist options
  • Save dcragusa/1e58f7b4bb14a3360c855e7349006863 to your computer and use it in GitHub Desktop.
Save dcragusa/1e58f7b4bb14a3360c855e7349006863 to your computer and use it in GitHub Desktop.
A general error catching decorator to be applied to functions: includes an sql rollback and email notification
def error_handling(rollback_toggle=False):
def wrap(func: C) -> C:
@wraps(func)
def func_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
tb = sys.exc_info()[2]
exception_locals = tb.tb_next.tb_frame.f_locals
send_email = False if e.__class__ is ExpectedException else True
if rollback_toggle:
SqlSessionManager.session().rollback()
notified = '\n\nPress OK to notify the tech team.' if send_email else ''
show_message('Error: %s%s' % (str(e), notified), title='Exception', style='error')
text = str(e) + '\n\n' + traceback.format_exc() + '\n\n' + str(exception_locals)
print(text)
if send_email:
recipients = ['[email protected]', '[email protected]']
mail_tools.send_smtp_email(
'[%s][%s][%s] - Function %s in %s crashed' % (
ENVIRONMENT, system_tools.hostname(), user, func.__name__, func.__module__
), text, sender='[email protected]', recipient=recipients
)
return func_wrapper
return wrap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment