I am catching http errors using python, but I want to know the code of the error (e.g. 400, 403,..). Additionally I want to get the message of the error. However, I can't find those two attributes in the documentation. Can anyone help? Thank you.
try:
"""some code here"""
except urllib3.exceptions.HTTPError as error:
"""code based on error message and code"""
Assuming that you mean the description of the HTTP response when you said "the message of the error", you can use responses
from http.client
as in the following example:
import urllib3
from http.client import responses
http = urllib3.PoolManager()
request = http.request('GET', 'http://google.com')
http_status = request.status
http_status_description = responses[http_status]
print(http_status)
print(http_status_description)
...which when executed will give you:
200
OK
on my example.
I hope it helps. Regards.
The following sample code illustrates status code of the response and cause of the error:
import urllib3
try:
url ='http://httpbin.org/get'
http = urllib3.PoolManager()
response=http.request('GET', url)
print(response.status)
except urllib3.exceptions.HTTPError as e:
print('Request failed:', e.reason)
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