SilentSteel
SilentSteel

Reputation: 2434

How to catch this Python exception: error: [Errno 10054] An existing connection was forcibly closed by the remote host

I am trying to catch this particular exception (and only this exception) in Python 2.7, but I can't seem to find documentation on the exception class. Is there one?

[Errno 10054] An existing connection was forcibly closed by the remote host

My code so far:

try:
  # Deleting filename
  self.ftp.delete(filename)
  return True
except (error_reply, error_perm, error_temp):
  return False
except # ?? What goes here for Errno 10054 ??
  reconnect()
  retry_action()

Upvotes: 13

Views: 37678

Answers (3)

user2489743
user2489743

Reputation: 166

The error type is socket.error, the documentation is here. Try modiffying your code like this:

import socket
import errno  

try:
    Deleting filename
    self.ftp.delete(filename)
    return True
except (error_reply, error_perm, error_temp):
    return False
except socket.error as error:
    if error.errno == errno.WSAECONNRESET:
        reconnect()
        retry_action()
    else:
        raise

Upvotes: 15

tdelaney
tdelaney

Reputation: 77347

When you want to filter exceptions, the first step is to figure out the exception type and add it to an except clause. That's normally easy because python will print it out as part of a traceback. You don't mention the type, but it looks like socket.gaierror to me, so I'm going with that.

The next step is to figure out what is interesting inside of the exception. In this case, `help(socket.gaierror)' does the trick: there is a field called errno that we can use to figure out which errors we want to filter.

Now, rearrange your code so that the exception is caught inside a retry loop.

import socket

retry_count = 5  # this is configured somewhere

for retries in range(retry_count):
    try:
        # Deleting filename
        self.ftp.delete(filename)
        return True
    except (error_reply, error_perm, error_temp):
        return False
    except socket.gaierror, e:
        if e.errno != 10054:
            return False
        reconnect()
return False

Upvotes: 1

giovanni
giovanni

Reputation: 206

You may try doing something like :

try:
    # Deleting filename
    self.ftp.delete(filename)
    return True
except (error_reply, error_perm, error_temp):
    return False
except Exception, e:
    print type(e)  # Should give you the exception type
    reconnect()
    retry_action()

Upvotes: 1

Related Questions