Reputation: 2433
I see one of the methods in python uses raise_for_status()
:
def raise_for_status(self):
if 400 <= self.status_code < 500:
http_error_msg = (
f"{self.status_code} Client Error: {reason} for url: {self.url}"
)
elif 500 <= self.status_code < 600:
http_error_msg = (
f"{self.status_code} Server Error: {reason} for url: {self.url}"
)
if http_error_msg:
raise self.status_code, HTTPError(http_error_msg, response=self)
I want to add a try/except
block such that, I can handle the exception. However, it also raises the status code along with the exception.
Not sure, how can I capture the status code without modifying the existing code for rasei_for_status()
Upvotes: 2
Views: 37
Reputation: 195573
There is property Response.status_code
in the response. You can do:
import requests
url = "https://www.google.com/nonexistent_path"
try:
r = requests.get(url)
r.raise_for_status()
except requests.exceptions.HTTPError as err:
print("Status code:", r.status_code)
print("Error:", err)
Prints:
Status code: 404
Error: 404 Client Error: Not Found for url: https://www.google.com/nonexistent_path
Upvotes: 1