7

so I have an event loop which will run_until_complete my accept_connection method

@asyncio.coroutine
def accept_connection(self):
    assert self.server_socket is not None

    while True:
        client, addr = yield from self.loop.sock_accept(self.server_socket)
        asyncio.async(self.handle_connection(client, addr))

my handle_connection method looks like this

 def handle_connection(self, client, addr):
     #removed error checking

    while True:
        try:
            yield from asyncio.wait([con.handle_read_from_connection()], timeout=5.0)
        except (AssertionError, PacketException):
            print("Invalid packet detected!")

finally my handle_read_from_connection (currently) looks like this:

@asyncio.coroutine
def handle_read_from_connection(self):
    raise PacketException("hello")

therefore this method should always raise an error and hit the except block of the try catch statement and print invalid packet detected. Instead what happens is I get a traceback!

future: Task(<handle_read_from_connection>)<exception=PacketException('hello',)>
Traceback (most recent call last):
  File "/usr/lib/python3.4/asyncio/tasks.py", line 283, in _step
    result = next(coro)
  File "/some_path.py", line 29, in handle_read_from_connection
    raise PacketException("hello")
GameProtocol.GameProtocol.PacketException: hello

does anyone know what going on here? why is the try catch not working? and how can I get it so we can catch these errors

4

1 回答 1

10

您需要使用以下返回的值asyncio.wait()

import asyncio

class Error(Exception):
    pass

@asyncio.coroutine
def main():
    try:
        done, pending = yield from asyncio.wait([raise_exception()], timeout=1)
        assert not pending
        future, = done # unpack a set of length one
        print(future.result()) # raise an exception or use future.exception()
    except Error:
        print('got exception', flush=True)
    else:
        print('no exception', flush=True)

@asyncio.coroutine
def raise_exception(): # normally it is a generator (yield from)
                       #  or it returns a Future
    raise Error("message")

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

输出

got exception

当前的实现asyncio.coroutine假设如果一个函数不是生成器(就像你的情况一样),那么它返回一个 Future ,因此它应该被转换为一个生成器,因此调用raise_exception()不会引发异常,因为它只是创建了生成器对象(协程)。

然后asyncio.wait()产生它并完成一些等效的future.set_exception(exception)操作。

避免您看到的错误输出;您需要通过调用future.result()future.exception()直接使用异常。

于 2014-05-04T16:09:04.917 回答