【问题标题】:Unhandled exceptions in a RESTful API are not getting jsonify'edRESTful API 中未处理的异常没有被 jsonify 处理
【发布时间】: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?还是有其他方法可以做到这一点?

【问题讨论】:

标签: python rest exception resources flask


【解决方案1】:

Flask-Restful 有自己的错误处理程序,您从 /test2 看到的 JSON 输出是由扩展程序本身生成的。

如果您通过 Flask 的 handle_exception 调用注册新的异常处理程序,则可以覆盖 Flask-Restful 的异常。

【讨论】:

  • 米格尔,你能说得更具体一点吗?我们如何覆盖 Flask-Restful 的异常处理,也就是说重新激活 Flask 的 vanilla 异常处理来处理某种异常类型?
  • 看看 Flask-Restful redirects error handling through itself.与它们替换错误处理程序以在 Flask 之前调用它们相同的方式,您可以插入自己的错误处理程序,该处理程序在 Flask-Restul 之前调用。在您的处理程序中,您可以决定何时将错误传递给 Flask-Restful 以及何时自己处理。如果你想调用 Flask 的原始处理程序,那么在注册 Flask-Restful 之前复制这个处理程序。
【解决方案2】:

这是因为 Flask-Restful monkeypatch 默认 Flask.handle_user_exception 将具有 specific logic for Flask-Restful endpoints 和其他端点的默认行为。

【讨论】:

  • @sangeeth-saravanaraj 那么,您使用了什么样的解决方案?
  • 我现在不记得了,但也许你可以使用覆盖 error_router/handle_error:github.com/flask-restful/flask-restful/blob/…,或者发送一些处理程序,如 Api.__init__(error=YOUR THERE)。请查看此案例的文档。
猜你喜欢
  • 2011-11-19
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 2018-10-18
  • 2016-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多