Skip to content

Instantly share code, notes, and snippets.

@giampaolo
Created March 16, 2023 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giampaolo/905b38a5ea9d5179eb0138e2f37a01a8 to your computer and use it in GitHub Desktop.
Save giampaolo/905b38a5ea9d5179eb0138e2f37a01a8 to your computer and use it in GitHub Desktop.
Check whether an exception is a connection error
"""
Blog post:
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment