Python 异常未捕获

标签 python exception logging

我目前正在 Python 中使用套接字和 JSON,其中有以下代码:

class RCHandler(SocketServer.BaseRequestHandler):    
    def setup(self):
        pass

    def handle(self):
        raw = self.request.recv(1024)
        recv = raw.strip()

        if not recv:
            return

        # do some logging
        logging.debug("RECV: (%s)" % recv)

        try:
            data = json.loads(recv)
        except:
            logging.exception('JSON parse error: %s' % recv)
            return

        if recv == 'quit':
            return

问题是当我发送错误的 JSON 字符串时,例如'{"method": "test"',异常似乎被捕获,但我仍然得到以下回溯:

DEBUG: 20/09/2015 12:33:57 - RECV: ({"method": "test")
ERROR: 20/09/2015 12:33:57 - JSON parse error: {"method": "test"
Traceback (most recent call last):
  File "./remoteControl.py", line 68, in handle
    data = json.loads(recv)
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting object: line 1 column 17 (char 16)

我在这里缺少什么?如果我捕获异常,我不应该得到回溯,对吗?我的服务器类扩展了 ThreadingTCPServer(如果这与它有任何关系)。

当我运行另一个 python 脚本时:

#!/usr/bin/python

import json
import socket

d = '{"method": "test"'

try:
    data = json.loads(d)
except:
    print "fail"

它只打印“失败”并且不打印回溯。

最佳答案

确实捕获了异常,但您正在告诉logging通过使用 Logger.exception 来包含异常信息(其中包括回溯)方法在这里:

except:
    logging.exception('JSON parse error: %s' % recv)

来自method documentation :

Logs a message with level ERROR on the root logger. The arguments are interpreted as for debug(), except that any passed exc_info is not inspected. Exception info is always added to the logging message. This function should only be called from an exception handler.

强调我的

另请参阅 Formatter.formatException() documentation ;正是这个方法在这里进行异常格式化:

Formats the specified exception information (a standard exception tuple as returned by sys.exc_info()) as a string. This default implementation just uses traceback.print_exception(). The resulting string is returned.

traceback.print_exception() 这样做:

Print exception information and up to limit stack trace entries from traceback to file.

如果您不希望包含异常,请使用 logging.error()相反:

except:
    logging.error('JSON parse error: %s' % recv)

或提供自定义 Formatter subclass格式化异常信息而不进行回溯。

关于Python 异常未捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32673900/

相关文章:

python - Pygame 中的颜色碰撞检测

python - 有没有使用元素树从 xml 文件创建多个数据框的方法?

python - 使用 bool() 简化 'if' 语句

logging - 如何在 CaSTLe Windsor 工厂方法中获取请求类型?

linux - 运行 SSH session 并从客户端记录到文件 stdout,添加时间戳

python - SuperCollider 不启动 DotFox

java - 在 RunTimeException 的情况下如何在子类中声明父异常?

c++ - 捕获构造函数抛出的异常似乎是不可能的

java.sql.SQLException :[SQLITE_ERROR] SQL error or missing database (near "=":syntax error) 异常

ruby-on-rails - 登录在 rails 内外都使用的 gem