I am writing a decorator to apply to a function. It should catch any exception, and then raise a custom exception based on the original exception message. (This is because
I've faced this problem with tests that were decorated with my custom decorators.
I used following construct in decorator body to preserve original trace printed in unittests output:
try:
result = func(self, *args, **kwargs)
except Exception:
exc_type, exc_instance, exc_traceback = sys.exc_info()
formatted_traceback = ''.join(traceback.format_tb(
exc_traceback))
message = '\n{0}\n{1}:\n{2}'.format(
formatted_traceback,
exc_type.__name__,
exc_instance.message
)
raise exc_type(message)