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!

haneulkim
  • 4,406
  • 9
  • 38
  • 80
  • 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? – shiny Apr 15 '21 at 09: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. – haneulkim Apr 15 '21 at 09: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: https://de.wikipedia.org/wiki/HTTP-Statuscode – shiny Apr 15 '21 at 09:22
  • Yes, all standard http status code works however I want to make custom ones. – haneulkim Apr 15 '21 at 09:25
  • i see, thats probably not that simple, here is a discussion on creating custom codes: https://stackoverflow.com/questions/7996569/can-we-create-custom-http-status-codes. 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. – shiny Apr 15 '21 at 09:36

0 Answers0