1

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

sumanth shetty
  • 1,851
  • 5
  • 24
  • 57
  • 2
    Possible duplicate of [Correct way to try/except using Python requests module?](https://stackoverflow.com/questions/16511337/correct-way-to-try-except-using-python-requests-module) – Giacomo Alzetta Nov 05 '19 at 09:38

1 Answers1

3

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)
Linh Nguyen
  • 3,452
  • 4
  • 23
  • 67