Reputation: 71
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"""
Upvotes: 4
Views: 21555
Reputation: 397
Status codes come from the response, while HTTPError means urllib3 cannot get the response. Status codes 400+ will not trigger any exception from urllib3.
Upvotes: 3
Reputation: 63
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)
Upvotes: 4
Reputation: 369
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.
Upvotes: 11