返回处理异常

时间:2017-05-10 10:51:56

标签: python-3.x

我不明白为什么我的程序没有返回带有在try catch块中定义的错误代码的json响应。

json = request.json
return jsonify(controller.new_configuration(json))

这是我在Controller.py中的函数new_configuration

def new_configuration(self, data):

    try:
        self.config.read('system/settings.ini')
        self.config.set('service_configuration', 'servid', data['servID'])
        self.config.set('service_configuration', 'uri', data['uri'])
        self.config.set('service_configuration', 'res_temp_min', data['res_temp_min'])

        for param in data['modelParameters']:
            self.config.set('model_param', param['k'], param['v'])

        with open('system/settings.ini', 'w') as configfile:
            self.config.write(configfile)

    except TypeError as e:
        return {"rc": 1, "rcDesc": e}
    except ValueError as e:
        return {"rc": 1, "rcDesc": e}
    except KeyError as e:
        self.log.warning(e)
        return {"rc": 1, "rcDesc": e}
    except AttributeError as e:
        self.log.warning(e)
        return {"rc": 1, "rcDesc": e}

    return {"rc": 0, "rcDesc": "ok"}

我故意发送一个TypeError json,我猜它应该返回{“rc”:1,“rcDesc”:e}但它不是。 我得到了这个错误,应用程序中断了:

raise TypeError(repr(o) + " is not JSON serializable")
TypeError: KeyError('servID',) is not JSON serializable

1 个答案:

答案 0 :(得分:1)

因为e的类型是某种错误,您无法将其序列化为JSON

尝试:

return {"rc": 1, "rcDesc": repr(e)}

也可能没有必要单独捕获所有这些错误,具体取决于您正在做什么