I\'ve seen a lot of posts about stack trace and exceptions in Python. But haven\'t found what I need.
I have a chunk of Python 2.7 code that may raise an exception.
I defined following helper class:
import traceback
class TracedExeptions(object):
def __init__(self):
pass
def __enter__(self):
pass
def __exit__(self, etype, value, tb):
if value :
if not hasattr(value, 'traceString'):
value.traceString = "\n".join(traceback.format_exception(etype, value, tb))
return False
return True
Which I can later use like this:
with TracedExeptions():
#some-code-which-might-throw-any-exception
And later can consume it like this:
def log_err(ex):
if hasattr(ex, 'traceString'):
print("ERROR:{}".format(ex.traceString));
else:
print("ERROR:{}".format(ex));
(Background: I was frustraded because of using Promises together with Exceptions, which unfortunately passes exceptions raised in one place to a on_rejected handler in another place, and thus it is difficult to get the traceback from original location)