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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With