In python we get different exception for diff connection issues like ECONNREFUSED, ECONNRESET, EHOSTUNREACH etc. Is there any standard logic for identifying connection errors in python? Basically I am using suds for connecting to vmware WS SDK and I want to re-try session login on connection errors.
Asked
Active
Viewed 686 times
0
-
1How are you creating the connections? Using the `socket` module? Anyway on python3.3 the I/O exception hierarchy was rewritten(see the [what's new](http://docs.python.org/dev/whatsnew/3.3.html#pep-3151)). In particular you can use `ConnectionAbortedError`, `ConnectionRefusedError` and `ConnectionResetError`. In previous versions of python you should catch `IOError` and examine the error number. – Bakuriu Jun 26 '13 at 12:52
2 Answers
1
I faced exactly this problem today and I wrote a blog post about it: https://gmpy.dev/blog/2023/recognize-connection-errors
import errno, socket, ssl
# Network errors, usually related to DHCP or wpa_supplicant (Wi-Fi).
NETWORK_ERRNOS = frozenset((
errno.ENETUNREACH, # "Network is unreachable"
errno.ENETDOWN, # "Network is down"
errno.ENETRESET, # "Network dropped connection on reset"
errno.ENONET, # "Machine is not on the network"
))
def is_connection_err(exc):
"""Return True if an exception is connection-related."""
if isinstance(exc, ConnectionError):
# https://docs.python.org/3/library/exceptions.html#ConnectionError
# ConnectionError includes:
# * BrokenPipeError (EPIPE, ESHUTDOWN)
# * ConnectionAbortedError (ECONNABORTED)
# * ConnectionRefusedError (ECONNREFUSED)
# * ConnectionResetError (ECONNRESET)
return True
if isinstance(exc, socket.gaierror):
# failed DNS resolution on connect()
return True
if isinstance(exc, (socket.timeout, TimeoutError)):
# timeout on connect(), recv(), send()
return True
if isinstance(exc, OSError):
# ENOTCONN == "Transport endpoint is not connected"
return (exc.errno in NETWORK_ERRNOS) or (exc.errno == errno.ENOTCONN)
if isinstance(exc, ssl.SSLError):
# Let's consider any SSL error a connection error. Usually this is:
# * ssl.SSLZeroReturnError: "TLS/SSL connection has been closed"
# * ssl.SSLError: [SSL: BAD_LENGTH] bad length
return True
return False

Giampaolo Rodolà
- 12,488
- 6
- 68
- 60
0
Standard logic in python is to catch exceptions using try/except
construction: Handling Exception in Python

Alex G.P.
- 9,609
- 6
- 46
- 81
-
What I asked is, Is there a standard list of exceptions which denotes a connection issue. – Litty Jun 26 '13 at 12:21
-
It depends on package structure. For example, `suds` uses following exceptions:AttributeError, BuildError, Exception, KeyError, MethodNotFound, PathResolver.BadPath, PortNotFound, ServiceNotFound, StopIteration, TypeNotFound. All expcetions related to network raised as instance of Exception class. There is not special parent of network- or connection-related common exceptions parent like NetworkError. – Alex G.P. Jun 26 '13 at 12:26