Python3 Catch errors when from self.connect(('

2019-08-29 16:49发布

Looks like asyncio is the module to use. I'll leave this question up anyway, because it doesn't look like there is a way to catch specific errors with asynchat.

class mysocket(asynchat.async_chat):
    terminator = b'\n'
    def __init__(self,sock=None):
        asynchat.async_chat.__init__(self,sock)
        self.create_socket()
        # Try always succeeds with self.connect
        try:
            self.connect(('badhost',6667))
            print('command always successful')
        except:
            print('This never gets printed')

How do I catch errors from the self.connect() method that causes an uncaught exception.

error: uncaptured python exception, closing channel <main.mysocket badhost:6667 at 0x7f0a03e66a58> (:[Errno 111] Connection refused [/usr/lib/python3.4/asyncore.py|read|83] [/usr/lib/python3.4/asyncore.py|handle_read_event|439] [/usr/lib/python3.4/asyncore.py|handle_connect_event|447])

All that is left to try is overwrite the handle_connect_event() method and put asyncore.handle_connect_event(self). I would like to get a professional answer to this dilemma.

1条回答
疯言疯语
2楼-- · 2019-08-29 17:45

Try to override default handle_error method:

def handle_error(self):
    t, v, tb = sys.exc_info()
    if t == socket.error:
        # do smth with it
        print("Connect error")
查看更多
登录 后发表回答