Reputation: 2181
Hi I am using the following code
def request_task(url, data, headers):
try:
re = requests.post(url, json=data, headers=headers)
re.raise_for_status()
except requests.exceptions.HTTPError as e:
print (e.response.text)
I am able to handle the http error but not able to to handle connection errors How can i modify my code to handle the types connection error ? Thank you
Upvotes: 2
Views: 3176
Reputation: 569
Instead of catching all exception with except Exception as e
, which by the way raises a Too broad exception clause
in PyCharm, just catch requests
exceptions with requests.exceptions.RequestException
that is then main exception (see exceptions.py
in requests
package):
try:
re = requests.post(url, json=data, headers=headers)
re.raise_for_status()
except requests.exceptions.RequestException as e:
print(e)
Upvotes: 1
Reputation: 3920
you can catch the connection error with requests.exceptions.ConnectionError
But i don't recommend using too many excepts unless you specifically want to. Here my recommend to catch the exceptions if you using try catch:
try:
re = requests.post(url, json=data, headers=headers)
re.raise_for_status()
except Exception as e:
print(e)
Upvotes: 3