Python: Exception decorator. How to preserve stacktrace

后端 未结 2 2025
伪装坚强ぢ
伪装坚强ぢ 2020-12-24 08:15

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

2条回答
  •  难免孤独
    2020-12-24 08:25

    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)
    

提交回复
热议问题