简体   繁体   English

没有抓住Python异常

[英]Python exception not caught

I am currently playing with sockets and JSON in Python where I have the following code: 我目前正在使用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

The problem is that when I send a faulty JSON string, eg '{"method": "test"' , the exception seems to be caught, but I still get the following traceback: 问题是,当我发送一个错误的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)

What am I missing here? 我在这里错过了什么? I am not supposed to get a traceback if I catch the exception right? 如果我抓住异常,我不应该得到回溯吗? My server class extends ThreadingTCPServer if that has anything to do with it. 我的服务器类扩展了ThreadingTCPServer,如果它与它有关。

When I ran another python script: 当我运行另一个python脚本时:

#!/usr/bin/python

import json
import socket

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

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

It only prints "fail" and no traceback. 它只打印“失败”而没有追溯。

You did catch the exception, but you are telling logging to include the exception information (which includes the traceback), by using the Logger.exception method here: 确实捕获了异常,但是您通过使用Logger.exception方法告诉logging包含异常信息(包括回溯):

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

From the method documentation : 方法文档

Logs a message with level ERROR on the root logger. 在根记录器上记录级别为ERROR的消息。 The arguments are interpreted as for debug() , except that any passed exc_info is not inspected. 参数被解释为debug() ,除了没有检查任何传递的exc_info Exception info is always added to the logging message . 始终将异常信息添加到日志记录消息中 This function should only be called from an exception handler. 只应从异常处理程序调用此函数。

Emphasis mine . 强调我的

Also see the Formatter.formatException() documentation ; 另请参阅Formatter.formatException()文档 ; it is this method that does the exception formatting here: 这是在这里执行异常格式化的方法:

Formats the specified exception information (a standard exception tuple as returned by sys.exc_info() ) as a string. 将指定的异常信息(由sys.exc_info()返回的标准异常元组)格式化为字符串。 This default implementation just uses traceback.print_exception() . 此默认实现仅使用traceback.print_exception() The resulting string is returned. 返回结果字符串。

and traceback.print_exception() does this: traceback.print_exception()执行此操作:

Print exception information and up to limit stack trace entries from traceback to file . 打印异常信息,最多限制堆栈跟踪条目从回溯文件

If you did not want the exception to be included, use logging.error() instead: 如果您不希望包含异常,请使用logging.error()代替:

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

or provide a custom Formatter subclass that formats the exception information without the traceback. 或提供自定义Formatter子类 ,该子类在没有回溯的情况下Formatter异常信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM