【发布时间】:2013-10-11 19:04:51
【问题描述】:
我有以下代码 - 它有一个 http 处理函数 (func1) 和一个 RESTful API (func2),它们可以通过 URL /test1 和 /test2 访问。我有一个异常处理函数(exception_handler),它由app.errorhandler() 装饰,以确保所有未处理的异常都被jsonify 并作为响应发送回来。
from flask import Flask, jsonify
from flask.ext.restful import Resource, Api
app = Flask(__name__)
api = Api(app)
@app.errorhandler(Exception)
def exception_handler(e):
return jsonify(reason=e.message), 500
@app.route("/test1", methods=["GET"])
def func1():
raise Exception('Exception - test1')
class func2(Resource):
def get(self):
raise Exception('Exception - test2')
api.add_resource(func2, '/test2')
if __name__ == "__main__":
app.run(debug=True)
现在将未处理的异常转换为带有包含异常消息的 JSON 的 HTTP 响应对于普通的 http 处理程序函数(即 func1)可以正常工作,但对于 RESTful API(使用资源创建)(即 func2)则不起作用。
func1 可以正常工作:
$ curl http://127.0.0.1:5000/test1 -X GET
{
"reason": "Exception - test1"
}
使用func2,我们得到的是{"message": "Internal Server Error", "status": 500},而不是{"reason": "Exception - test2"}
$ curl http://127.0.0.1:5000/test2 -X GET
{
"message": "Internal Server Error",
"status": 500
}
所以问题是为什么 RESTful API 中未处理的异常没有使用app.errorhandler 转换为 JSON?还是有其他方法可以做到这一点?
【问题讨论】:
-
在我看来,FR 中的错误处理太有限了。另请参阅github.com/twilio/flask-restful/pull/284。
标签: python rest exception resources flask