Python3 Catch errors when from self.connect(('badhost',6667))

主宰稳场 提交于 2020-01-16 18:35:30

问题


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:


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")


来源:https://stackoverflow.com/questions/29714822/python3-catch-errors-when-from-self-connectbadhost-6667

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!