sockets - Python3 从 self.connect(('badhost' ,6667) 时捕获错误

标签 sockets python-3.x error-handling exception-handling asyncore

看起来 asyncio 是要使用的模块。无论如何,我都会留下这个问题,因为看起来没有办法用 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')

如何从导致未捕获异常的 self.connect() 方法中捕获错误。

错误:未捕获的 python 异常,关闭 channel < 主要 .mysocket badhost:6667 at 0x7f0a03e66a58> (:[Errno 111] 连接被拒绝 [/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])

剩下要做的就是覆盖handle_connect_event() 方法并放入asyncore.handle_connect_event(self)。我想得到一个专业的答案来解决这个难题。

最佳答案

尝试覆盖默认的 handle_error 方法:

def handle_error(self):
    t, v, tb = sys.exc_info()
    if t == socket.error:
        # do smth with it
        print("Connect error")

关于sockets - Python3 从 self.connect(('badhost' ,6667) 时捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29714822/

相关文章:

java - 来自 Linux-Java 线程转储的套接字信息

database - Python 3和Sybase等数据库

magento - Magento 502错误的网关,仅在可配置产品上

sql-server - 希望确保在我的存储过程中正确捕获了错误

bash - 有没有机会在第一个错误时停止chown?

ServerSocket.accept() 返回的 Java 客户端套接字

c# - "A connection attempt failed because the connected party did not properly respond after a period of time"使用 WebClient

c - 绑定(bind)失败并出现无效参数错误

python - 打开文件以使用truncate进行读写

python-3.x - 在tensorflow 2中加载ModelCheckpoint