I am catching exceptions like this,
def get_url_fp(image_url, request_kwargs=None):
response = requests.get(some_url, **request_kwargs)
response.raise_for_status()
return response.raw
try:
a = "http://example.com"
fp = get_url_fp(a)
except HTTPError as e:
# Need to check its an 404, 503, 500, 403 etc.
Python exceptions do not have "codes". You can create a custom exception that does have a property called code and then you can access it and print it as desired. This answer has an example of adding a code property to a custom exception.
In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception. In the rare event of an invalid HTTP response, Requests will raise an HTTPError exception. If a request times out, a Timeout exception is raised.
February 21, 2019. Sometimes when you try to visit a web page, you're met with an HTTP error message. It's a message from the web server that something went wrong. In some cases it could be a mistake you made, but often, it's the site's fault. Each type of error has an HTTP error code dedicated to it.
The HTTPError
carries the Response
object with it:
def get_url_fp(image_url, request_kwargs=None):
response = requests.get(some_url, **request_kwargs)
response.raise_for_status()
return response.raw
try:
a = "http://example.com"
fp = get_url_fp(a)
except HTTPError as e:
# Need to check its an 404, 503, 500, 403 etc.
status_code = e.response.status_code
If you need only status_code or message error. You can use this code:
try:
[YOUR CODE]
except requests.exceptions.HTTPError as err:
print(err.response.status_code)
print(err.response.text)
Reference: Source code for requests.exceptions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With