mafrasi2
mafrasi2

Reputation: 322

How to handle ConnectionError in Python

Currently I have the problem that I get a NameError for the following code:

try:
    # some network programming raising an exception
except ConnectionError:
    # some error handling

This does not work, because you have to import ConnectionError from some module, which is not mentioned in the documentation (maybe I'm just blind?). All I found is this, but it refers to another request library.

Upvotes: 5

Views: 14992

Answers (2)

dfrankow
dfrankow

Reputation: 21459

I had a similar problem. I'm using python 3.11, the code block you have worked without an import because ConnectionError is in a python built-in. However, the exception was not being caught.

It turns out requests 2.31.0 is using its own ConnectionError (!). Once my except clause used requests.exceptions.ConnectionError, it worked for me.

Upvotes: 2

abarnert
abarnert

Reputation: 366093

All of the exceptions in the standard library that are expected to be "generally usable" are built-ins, and are documented in the Built-in Exceptions part of the library reference.

In 3.3, that includes this one:

exception ConnectionError

A base class for connection-related issues.

Subclasses are BrokenPipeError, ConnectionAbortedError, ConnectionRefusedError and ConnectionResetError.

But this is a built-in. So this should work:

except ConnectionError:

In 3.0-3.2, there is no such exception as ConnectionError. Nothing in the stdlib raises anything of that name. So there's no point in trying to handle it. (See PEP 3151 for an explanation of how OSError and IOError were reorganized between 3.2 and 3.3.)

The 3.2 equivalent of ConnectionError is OSError with certain errno values. So, what you want is something like:

except OSError as e:
    if e.errno not in (EPIPE, ESHUTDOWN, ECONNABORTED, ECONNREFUSED, ECONNRESET):
        raise
    # whatever you wanted to do for ConnectionError.

Meanwhile, in the future, when you don't know what kind of exception you need to handle, it's pretty easy to test. First, write some test code that handles any exception by logging the qualified name of the exception type. Then take the type out of the log and use that in your real code.

try:
    code_that_raises()
except Exception as e:
    print(type(e), type(e).__qualname__, whatever_else_looks_useful(e))

Upvotes: 5

Related Questions