6

In my code, I've made some post requests. How can I catch connection refused error in that call?

   try:
        headers = {'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'}
        response = requests.request("POST", local_wallet_api + "v1/wallet/get_public_keys", headers=headers)
        res = json.loads(response.text)


   except Exception as e:
        if e.errno == errno.ECONNREFUSED:
            print("connection refused")
            sys.exit(141)

I've tried the above code, but it is not working as it says e has no errno parameter. Is there any proper way to handle this kind of error?

Prayag k
  • 647
  • 9
  • 23

3 Answers3

7
from requests.exceptions import ConnectionError


   try:
        headers = {'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'}
        response = requests.request("POST", local_wallet_api + "v1/wallet/get_public_keys", headers=headers)
        res = json.loads(response.text)

   except ConnectionError:
        sys.exit(141)
Umesh
  • 941
  • 5
  • 12
4

you can use requests.exceptions.RequestException as your exception.

Example:

except requests.exceptions.RequestException as e:
    # exception here

For the list of requests exceptions, check requests.exception documentation. You can refer to this link.

Jethro Sandoval
  • 266
  • 1
  • 7
1

take a look at this.

you can get the errno by e.args[0].reason.errno.

also use this except:

except requests.exceptions.ConnectionError as e: