5

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 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.