python捕获的异常仍然升起

时间:2017-11-22 08:37:04

标签: python exception

这是我第一次在stackoverflow上提问。关于我的英语不好,英语不是我的母语。

我写了一个像这样的try / except子句:

try:
    hostname = result["hostname"]
except Exception as e:
    logger.error(e)
    return {"retcode":1,"description":e}

如果结果中没有“hostname”键,则会出现KeyError异常。当我运行代码时,我看到异常已被捕获,因为logger.error(e)在我的日志文件中放置了一个日志。但它仍然引发了一个例外,没有返回这个{“retcode”:1,“description”:“failed”}。

异常信息如下:

Traceback (most recent call last):
  File "/home/claire/myflask/venv/lib/python3.5/site-packages/flask/app.py",              line 1612, in full_dispatch_request
  rv = self.dispatch_request()
  File "/home/claire/myflask/venv/lib/python3.5/site-packages/flask/app.py", line 1598, in dispatch_request
  return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/claire/myflask/venv/lib/python3.5/site-packages/flask_restful/__init__.py", line 484, in wrapper
  return self.make_response(data, code, headers=headers)
  File "/home/claire/myflask/venv/lib/python3.5/site-packages/flask_restful/__init__.py", line 513, in make_response
  resp = self.representations[mediatype](data, *args, **kwargs)
  File "/home/claire/myflask/venv/lib/python3.5/site-packages/flask_restful/representations/json.py", line 21, in output_json
  dumped = dumps(data, **settings) + "\n"
  File "/usr/lib/python3.5/json/__init__.py", line 230, in dumps
  return _default_encoder.encode(obj)
  File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
  chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
  return _iterencode(o, 0)
  File "/usr/lib/python3.5/json/encoder.py", line 179, in default
  raise TypeError(repr(o) + " is not JSON serializable")
  TypeError: KeyError('hostname',) is not JSON serializable

我正在使用Python 3.5.2和Flask 0.12.2以及Flask-RESTful 0.3.6。 此代码位于烧瓶中。 完整的代码是这样的:

itf.py

import json
import requests
import time
import os,sys,re
import subprocess
import docker

def dosomething():
    do something.....
    return result    //result is a json.

api.py

from flask_restful import Resource, reqparse
from .mylogger import logger
from itf import dosomething

class TheRestAPI(Resource):
    def get(self, param):
        result = dosomething(param)

        try:
            hostname = result["hostname"]
        except Exception as e:
            logger.error(e)
            return {"retcode":1,"description":e}

        do other things .....
        return {"retcode":0,"description":"success"}

当我使用get请求调用此restAPI时,我得到了响应:

{"message": "Internal Server Error"}

我不知道为什么它在这里执行“logger.error(e)”,但是不返回下一个语句,为什么我使用“Exception as e”无法捕获KeyError异常。< / p>

然后我尝试了这个:

try:
    hostname = result["hostname"]
except Exception as e:
    logger.error(e)
    logger.error(str(type(e)))
    return {"retcode":1,"description":"failed"}
except KeyError as e:
    logger.info("second except.......")
    return {"retcode":1,"description":"failed"}
except TypeError as e:
    logger.info("third except.......")
    return {"retcode":1,"description":"failed"}

仍然无法捕获KeyError异常。

这是我的记录器模块:

import sys
import logging
from logging.handlers import RotatingFileHandler


LOG_PATH_FILE = '%s/app/agent.log'%sys.path[0]
LOG_MODE = 'a'
LOG_MAX_SIZE = 1*1024*1024 # 1M per file
LOG_MAX_FILES = 4
LOG_LEVEL = logging.INFO
LOG_FORMAT = "%(asctime)s %(levelname)-10s[%(filename)s:%(lineno)d(%(funcName)s)] %(message)s"

handler = RotatingFileHandler(LOG_PATH_FILE, LOG_MODE, LOG_MAX_SIZE, LOG_MAX_FILES)
formatter = logging.Formatter(LOG_FORMAT)
handler.setFormatter(formatter)

logger = logging.getLogger()

logger.setLevel(LOG_LEVEL)
logger.addHandler(handler)

1 个答案:

答案 0 :(得分:0)

你没有KeyError,但在追溯中没有TypeError。

你没有自定义logger.error功能吗?还是自定义形成者?

错误来自此行imho