Get exception description and stack trace which caused an exception, all as a string

前端 未结 11 1958
旧巷少年郎
旧巷少年郎 2020-11-30 16:22

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.

11条回答
  •  死守一世寂寞
    2020-11-30 16:46

    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)

提交回复
热议问题