Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch a connection refused error in a proper way?

Tags:

python

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?

like image 318
Prayag k Avatar asked Mar 29 '19 09:03

Prayag k


3 Answers

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)
like image 159
Umesh Avatar answered Oct 12 '22 02:10

Umesh


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.

like image 26
Jethro Sandoval Avatar answered Oct 12 '22 02:10

Jethro Sandoval


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:
like image 20
Mark SuckSinceBirth Avatar answered Oct 12 '22 02:10

Mark SuckSinceBirth