0

I want to get response status code if an error occurred

try:
    r = requests.post('site.com')
except (requests.RequestException) as e:
    print(r.status_code)

i can't do that

I also know about

r.raise_for_status()

But Exception raised before request so i can't do that

Mark
  • 69
  • 1
  • 9
  • 3
    If an exception was raised before/during the request then there is no response status code because there is no response. – DeepSpace Sep 16 '19 at 10:21
  • you should look at this [question](https://stackoverflow.com/questions/15258728/requests-how-to-tell-if-youre-getting-a-404) it may help you to understand how to get the status code of a request – Yannick Guéhenneux Sep 16 '19 at 10:22
  • @DeepSpace what about "400 Bad Request"? – Mark Sep 16 '19 at 10:24
  • if you get an exception maybe post the exception trace. exceptions indicate something in the code went wrong. Getting a bad response 400 would still be a valid response obejct so shouldnt cause an exception – Chris Doyle Sep 16 '19 at 10:24
  • @Chris Doyle i'm trying to handle all RequestException like MissingSchema, ConnectionError, ConnectTimeout e.t.c. And i want to return correct status code – Mark Sep 16 '19 at 10:28
  • ok so just think about what you said, lets use connection error / connection timeout. How can you expect to get an http response code if you never succesfully made a request in the first place. the response code is set by the server when it returns an http response. if you have a connection error or time out than like deepspace said in the case of that exception there would be no status code – Chris Doyle Sep 16 '19 at 10:29
  • @Chris Doyle. Ok i get it. thank you, so if i want to log it i shouldn't log status code? – Mark Sep 16 '19 at 10:36
  • 2
    yeah if something went wrong when calling `requests.post(` then it means a request was never sent to there will be no response so no status code – Chris Doyle Sep 16 '19 at 10:40

0 Answers0