Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot catch ConnectionError with requests

I'm doing this:

import requests
r = requests.get("http://non-existent-domain.test")

And getting

ConnectionError: HTTPConnectionPool(host='non-existent-domain.test', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x10b0170f0>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))

However, if I try to catch it like this:

try:
    r = requests.get("http://non-existent-domain.test")
except ConnectionError:
    print("ConnectionError")

Nothing changes, I still have ConnectionError unhandled. How to catch it properly?

like image 285
Ilya V. Schurov Avatar asked Dec 06 '16 08:12

Ilya V. Schurov


People also ask

How do I fix my ConnectionError?

To fix the error, click Connect on the page you try to open. You'll see this error if your computer or mobile device's date and time are inaccurate. To fix the error, open your device's clock. Make sure the time and date are correct.

What is ConnectionError?

Connection errors can occur for a variety of reasons. For example, a failure in any of the internal connections described in How Connection Between the Application and DBMS Server Is Established results in a connection error. How connection errors are reported depends on where the failure occurs.

How do you raise an unauthorized exception in Python?

If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call Response. raise_for_status. That will raise an HTTPError, if the response was an http error. The exception list on the Request website isn't complete.


1 Answers

That's a different ConnectionError. You are catching the built-in one, but requests has its own. So this should be

try:
    r = requests.get("http://non-existent-domain.test")
except requests.ConnectionError:
    print("ConnectionError")

# Output: ConnectionError
like image 193
Ilya V. Schurov Avatar answered Oct 01 '22 19:10

Ilya V. Schurov