sumanth shetty
sumanth shetty

Reputation: 2181

How to handle exception with request.post() method in python

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

Answers (2)

gluttony
gluttony

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

Linh Nguyen
Linh Nguyen

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

Related Questions