Python Exception cought但反正打印堆栈跟踪

时间:2018-05-09 11:31:59

标签: python-3.x exception exception-handling

我试图理解为什么堆栈跟踪会被打印出来 虽然例外被抓住了。以下是不同方法的示例:

方法1

//right before fetching JSON
boolean thereIsAnyUpdatesInJSON = checkYourDictionaryJsonIfThereAreAnyUpdates();
if(!isDictionaryDatabaseAvailable && thereIsAnyUpdatesInJSON){
     fetchYourDictJson();
}

方法2

import soco
try:
    ... code that can result with the exception...
except soco.exceptions.SoCoUPnPException as e:
    logger.warning("Exception caught. Not expecting trace")

方法3

from soco.exceptions import SoCoUPnPException
try:
    ... code that can result with the exception...
except SoCoUPnPException as e:
    logger.warning("Exception caught. Not expecting trace")

它们都会导致同样的错误:

try:
    ... code that can result with the exception...
except Exception as e:
    logger.warning("Exception caught. Not expecting trace")

我希望只打印ERROR [soco.services:410] UPnP Error 701 received: Transition not available from 10.10.10.114 Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/soco/services.py", line 408, in send_command self.handle_upnp_error(response.text) File "/usr/lib/python3.5/site-packages/soco/services.py", line 469, in handle_upnp_error error_xml=xml_error soco.exceptions.SoCoUPnPException: UPnP Error 701 received: Transition not available from 10.10.10.114 WARNING [senic_hub.nuimo_app.components.sonos:180] Exception caught. Not expecting trace 部分而不是整个痕迹。

更新

删除logger.warning("Exception caught. Not expecting trace")语句,在这种情况下try/catch被提升两次。

异常代码:https://github.com/SoCo/SoCo/blob/release-0.14/soco/exceptions.py#L22

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

正确捕获异常。查看Logger课程的文档。按照您的方式使用它会导致默认打印异常信息(如debug部分所述; infowarning等级也使用相同的行为)

有三个关键字参数(Python 3)可用于调整此行为:

  • exc_info - 导致将异常信息添加到日志消息中
  • stack_info - 导致堆栈信息被添加到日志消息仅限Python 3
  • extra - 接受字典以填充用于记录事件的__dict__的{​​{1}}。

要抑制堆栈和异常信息,请尝试以下操作:

LogRecord