Skip to content
Advertisement

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:

@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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement