python exception message capturing

前端 未结 11 1672
醉梦人生
醉梦人生 2020-12-12 09:06
import ftplib
import urllib2
import os
import logging
logger = logging.getLogger(\'ftpuploader\')
hdlr = logging.FileHandler(\'ftplog.log\')
formatter = logging.Form         


        
相关标签:
11条回答
  • 2020-12-12 09:29

    Updating this to something simpler for logger (works for both python 2 and 3). You do not need traceback module.

    import logging
    
    logger = logging.Logger('catch_all')
    
    def catchEverythingInLog():
        try:
            ... do something ...
        except Exception as e:
            logger.error(e, exc_info=True)
            ... exception handling ...
    

    This is now the old way (though still works):

    import sys, traceback
    
    def catchEverything():
        try:
            ... some operation(s) ...
        except:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            ... exception handling ...
    

    exc_value is the error message.

    0 讨论(0)
  • 2020-12-12 09:30

    You can try specifying the BaseException type explicitly. However, this will only catch derivatives of BaseException. While this includes all implementation-provided exceptions, it is also possibly to raise arbitrary old-style classes.

    try:
      do_something()
    except BaseException, e:
      logger.error('Failed to do something: ' + str(e))
    
    0 讨论(0)
  • 2020-12-12 09:41

    If you want the error class, error message, and stack trace, use sys.exc_info().

    Minimal working code with some formatting:

    import sys
    import traceback
    
    try:
        ans = 1/0
    except BaseException as ex:
        # Get current system exception
        ex_type, ex_value, ex_traceback = sys.exc_info()
    
        # Extract unformatter stack traces as tuples
        trace_back = traceback.extract_tb(ex_traceback)
    
        # Format stacktrace
        stack_trace = list()
    
        for trace in trace_back:
            stack_trace.append("File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]))
    
        print("Exception type : %s " % ex_type.__name__)
        print("Exception message : %s" %ex_value)
        print("Stack trace : %s" %stack_trace)
    

    Which gives the following output:

    Exception type : ZeroDivisionError
    Exception message : division by zero
    Stack trace : ['File : .\\test.py , Line : 5, Func.Name : <module>, Message : ans = 1/0']
    

    The function sys.exc_info() gives you details about the most recent exception. It returns a tuple of (type, value, traceback).

    traceback is an instance of traceback object. You can format the trace with the methods provided. More can be found in the traceback documentation .

    0 讨论(0)
  • 2020-12-12 09:42

    There are some cases where you can use the e.message or e.messages.. But it does not work in all cases. Anyway the more safe is to use the str(e)

    try:
      ...
    except Exception as e:
      print(e.message)
    
    0 讨论(0)
  • 2020-12-12 09:42

    Using str(e) or repr(e) to represent the exception, you won't get the actual stack trace, so it is not helpful to find where the exception is.

    After reading other answers and the logging package doc, the following two ways works great to print the actual stack trace for easier debugging:

    use logger.debug() with parameter exc_info

    try:
        # my code
    except SomeError as e:
        logger.debug(e, exc_info=True)
    

    use logger.exception()

    or we can directly use logger.exception() to print the exception.

    try:
        # my code
    except SomeError as e:
        logger.exception(e)
    
    0 讨论(0)
  • 2020-12-12 09:42

    for the future strugglers, in python 3.8.2(and maybe a few versions before that), the syntax is

    except Attribute as e:
        print(e)
    
    0 讨论(0)
提交回复
热议问题