我目前正在 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)
Logs a message with level
ERROR
on the root logger. The arguments are interpreted as fordebug()
, except that any passedexc_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 usestraceback.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/