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

后端 未结 3 959
旧时难觅i
旧时难觅i 2020-12-29 10:22

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?

相关标签:
3条回答
  • 2020-12-29 10:55

    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
    
    0 讨论(0)
  • 2020-12-29 11:09

    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()
    
    0 讨论(0)
  • 2020-12-29 11:12

    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
    
    0 讨论(0)
提交回复
热议问题