0

I am using python 3.8, Flask 1.1.2

While trying to handle errors can't figure out a way to return status code and break code when error is found.

When everything runs fine, program return statement is as follows return jsonify({'status':'success', 'prediction':pred}), 200

which allow me to access status_code

response = requests.post(url_path, json=data)
print(response.status_code)
>>> 200

However when error arise before reaching end of code I've tried to handle error like this:

code....
try:
    code
except KeyError:
    return jsonify({'error_message':'something wrong with input'}), 10
code...
return jsonify({"status":"success!", "best_actions":final_actions}), 200

When except statement is executed it outputs ConnectionError: ('Connection aborted.', BadStatusLine('HTTP/1.0 10 UNKNOWN\r\n')) which seems to happen when python client receives empty response according to Connection aborted.', BadStatusLine("''",) on server?

changing except statement like:

expect KeyError:
    return jsonify({'error_message':'something wrong with input'})

allow me to obtain response.json() however cannot get response.status_code.

returning with http status_code works:

expect KeyError:
    return jsonify({'error_message':'something wrong with input'}), 1xx

above code works fine however I am trying to create custom status_codes therefore I can add detailed reason and solution in my documentation.

Any help or guide to helpful resource would be greatly appreciated, thanks!

5
  • can you confirm that you are getting the KeyError and returning the disired response? Maybe you get another error type thus not sending the right response? Commented Apr 15, 2021 at 9:15
  • Yes I am positive it returns KeyError. Verified it by using debugger and found that when I try to access 1 in dictionary there is no such key. Commented Apr 15, 2021 at 9:16
  • ok, thats good, another question is that i've never seen a status code 10 in a response have you tried to return something standard like 100: de.wikipedia.org/wiki/HTTP-Statuscode Commented Apr 15, 2021 at 9:22
  • Yes, all standard http status code works however I want to make custom ones. Commented Apr 15, 2021 at 9:25
  • i see, thats probably not that simple, here is a discussion on creating custom codes: stackoverflow.com/questions/7996569/…. To quote the answer for future reference: Yes, as long as you respect the class -- that is, 2xx for success, 4xx for Client error, etc. Commented Apr 15, 2021 at 9:36

0

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.