from typing import Callable def exit_msg(code=0, msg=None): if msg is not None: print(msg) exit(code) def exec_and_log_error(exec: Callable, name=None, exit_on_err = True, reraise=False): ''' Executes a callable within a 'try/except' block; if an exception occurs, logs it and optionally exits the program, and/or re-raises the exception ''' def fmt_name(name): if name is None: return 'anonymous fn' try: return str(name) except: return 'fn-name-caused-error' try: exec() except Exception as e: msg = f"Error executing '{fmt_name(name)}': {e}" if exit_on_err: exit_msg(1, msg=msg) else: print(msg) if reraise: raise e