I have the following code - It has a http handler function (func1)
and a RESTful API (func2)
and they are reachable through URLs /test1
and /test2
. I have a exception handler function (exception_handler)
which is decorated by app.errorhandler()
to ensure that all unhandled exceptions are jsonify'ed and sent back as 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 an unhandled exception to a HTTP response with a JSON containing exception message works fine for a normal http handler function i.e. func1
but the same does not work for a RESTful API (created using Resource) i.e func2
.
The following works fine as expected with func1
:
$ curl http://127.0.0.1:5000/test1 -X GET
{
"reason": "Exception - test1"
}
With func2
we are getting a {"message": "Internal Server Error", "status": 500}
instead of {"reason": "Exception - test2"}
$ curl http://127.0.0.1:5000/test2 -X GET
{
"message": "Internal Server Error",
"status": 500
}
So the question is why the unhandled exceptions in RESTful API is not converted to JSON using app.errorhandler
? or is there any other way of doing this?
This because Flask-Restful
monkeypatch default Flask.handle_user_exception
which will have specific logic for Flask-Restful
endpoints and default behaviour for other endpoints.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With