Search code examples
python-3.xflaskerror-handlingflask-restfulrest

Jsonify Exception errors


While trying to handle errors in Flask Rest API, i would like to return the json version of error message and status code. i tried the following

@app.route("/model/test/",methods=["GET"])
def show():
    try:
        num=request.args['num']
        return jsonify({'result':num,'response':'200 OK'})
    except Exception as e:


        return jsonify({'error':e})

and when i hit the GET method with http://localhost:5000/model/test/?ummm=30. i got a error exceptions can't be jsonified any help on how to give error output as i wish?


Solution

  • json does not support many formats. Python decoding/encoding rules can be found here. I would propose to extract the text from the exception and add a status code, maybe "error" : "Message: {}, status 400 Bad request".format(e)? Or you can add a status-code separately.