I have the following code: it has the http handler function (func1)and the RESTful API (func2), and they are accessible through the URL /test1and /test2. I have an exception handler function (exception_handler)that is decorated app.errorhandler()to ensure that all unhandled jsonify'ed exceptions are sent back as a response.
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)
Now, converting the unhandled exception to an HTTP response with a JSON exception message works fine for the normal HTTP handler function, i.e. func1, but the same does not work for the RESTful API (created using Resource), that is func2.
The following works perfectly, as expected, with 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? ?