次のコードがあります。http ハンドラー関数(func1)
と RESTful API(func2)
があり、URL/test1
と/test2
. 処理されていないすべての例外がjsonifyされ、応答として返されるようにするために(exception_handler)
装飾された例外ハンドラー関数があります。app.errorhandler()
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 で未処理の例外が JSON に変換されない理由app.errorhandler
です。またはこれを行う他の方法はありますか?