Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flask handling multiple errors

I have a simple app made in Flask. It uses only POST method.
It takes 2 numbers (in json) and adds them up.

{"a": 1, "b": 1}

The application responds with the sum of these numbers (also in json).

{"sum": 2}

The code looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@appFlask.route('sum', methods=['POST'])
def result():
    data = request.get_json()
    return jsonify({'sum': data['a'] + data['b']})

I would like to do error handling. The problem is that there are a lot of these errors, e.g. for the following calls, they should return "400 Bad Request" or if the file isn’t in json.

{"a":1, "b":1, "c":1}
{"a", "a":1, "b":1}
{}
{"a":1}
{"a":0, "b":1}

How can i make it in the simplest way? Is there a way to do this in one function?

>Solution :

You can use catch the error and then you can return "400 Bad Request" and return an example of data and it’s validations to the user.

@appFlask.route('sum', methods=['POST'])
def result():
    try:
       data = request.get_json()
       # check if a or b is not 0
       if data['a'] == 0 or data['b'] == 0:
           raise Exception("Error occurred")
       return jsonify({'sum': data['a'] + data['b']})
    except Exception as e:
       return "400 Bad Request"
    

All the other calls mentioned in example will generate error which will be cached.

You don’t need to worry for {"a":1, "b":1, "c":1} as it will not affect the code but if you want to consider it bad request you need to do a check for it.

You surely need to do checks according to your needs as there is no built in function for that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading