Jsonify Exception errors

Viewed 2293

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?

2 Answers

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.

You could, for example:

def my_function():
    if request.method == 'PUT':
        try:
            a_test_function(request)
            return {
                'message': 'Request is a good request.',
                'status': 200,
            }, 200
        except ValueError as error:
            return {
                'message': "Bad request!",
                'status': 400,
                'Error': str(error),
            }, 400
        except:
            return {
                'message': "Bad request!",
                'status': 400,
                'Error': 'Unexpected error.',
            }, 400
Related