I'm working with Flask/Flask-RESTPlus to create a JSON-based REST API and as such I want to convert any errors from the server into the JSON format used. For whatever reason, the code I'm using doesn't seem to catch JSON decoding errors and instead outputs them directly with this response:
{
"message": "Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)"
}
From what I understand of Flask this should have come through as:
{
"errors": {
"message": "Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)"
}
}
I added a few debugging print statements and it's fairly clear to me that the response handler I added isn't actually catching anything since nothing gets output from the exception handler when a request with invalid JSON is made.
I've got the following code that replicates the issue:
from flask import Flask, jsonify, request, Response
from flask_restplus import Api, Resource
from werkzeug.exceptions import default_exceptions, HTTPException
import logging
def err_to_json(ex):
logging.warning("error handler")
logging.warning(ex)
code = 500
if isinstance(ex, HTTPException):
code = ex.code
return jsonify({"errors": {"message": str(ex)}}), code
app = Flask(__name__)
app.config["HOST"] = "0.0.0.0"
app.config["PORT"] = 80
api = Api(app)
@api.route("/test")
class TestEndpoint(Resource):
def post(self):
data = request.get_json()
logging.warning("data")
logging.warning(data)
if __name__ == "__main__":
for ex in default_exceptions:
app.register_error_handler(ex, err_to_json)
app.run(port=8000, host="0.0.0.0", debug=True)
This seems to be a slight adaptation of the pattern recommended by the Flask library. I've also tried directly handling the JSONDecodeError, but that made no difference either (app.register_error_handler(json.JSONDecodeError, err_to_json)).
Any idea why a request with invalid JSON causes a 400 error directly, instead of going through the error handler?
default_exceptions?errorproperty of the JSON result.logging.warning("error handler")?