Does Python support a way to display the same custom error message for every exception / raise / assert (no matter where the code broke)?
My current crack at it uses a decorator. I have a function main and it displays the traceback fine, but I want it to also print my_var (which is INSIDE the function scope) every time ANY error is thrown. So obviously there is a scope problem with this - it's just to illustrate what I want to do. Any ideas are appreciated.
import traceback
def exit_with_traceback(func, *args, **kwargs):
def wrap(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
# how do I get this to print my_var AND the traceback?
print(traceback.format_exc())
return wrap
@exit_with_traceback
def main(bar=1):
my_var = 'hello world' # variable specific to main()
return bar + 1
main(bar=None) # run main() to throw the exception