[英]Exception ignored in Tornado WebSocket on_message method
I have the following class: 我有以下课程:
class SessionHandler(tornado.websocket.WebSocketHandler):
@tornado.gen.coroutine
def on_message(self):
yield self.application.c.check("xxx@gmail.com")
The check() function is something like check()函数就像
@tornado.gen.coroutine
def check(self,id):
if id not in self.AUTH_METHOD.keys():
raise InvalidXX
InvalidXX
is a user defined exception that inherits from Exception
class. InvalidXX
是从Exception
类继承的用户定义的异常。
When this exception is raised nothing is displayed to the tornado console. 引发此异常时,龙卷风控制台不会显示任何内容。 However when I add try/except clauses around them the exception is picked up.
但是,当我在它们周围添加try / except子句时,会拾取异常。 I don't understand why this exception isn't being propagated to the console.
我不明白为什么这个异常没有传播到控制台。 Other exceptions Eg Duplicate key in MongoDB are propagated and shown to the console.
其他异常例如,MongoDB中的重复键被传播并显示到控制台。
[This answer applies to Tornado 4.4 and older. [这个答案适用于龙卷风4.4及更早版本。 As of Tornado 4.5
on_message
may be a coroutine and the code in the original question will work] 从Tornado 4.5
on_message
可能是一个协程,原始问题中的代码将工作]
Coroutines are called differently from regular functions (ie they must be called with yield
). 协程的调用与常规函数不同(即必须使用
yield
调用它们)。 Therefore, when you are defining a method to be called by the framework, you should only use a coroutine when the docs say something like "this method may be a coroutine". 因此,当您定义框架调用的方法时,只应在文档说“此方法可能是协程”时使用协程。
WebSocketHandler.on_message
may not be a coroutine (as of Tornado 4.3). WebSocketHandler.on_message
可能不是协程(从Tornado 4.3开始)。
Instead, you can use IOLoop.spawn_callback
to start an independent coroutine from your on_message
callback. 相反,您可以使用
IOLoop.spawn_callback
从on_message
回调中启动独立协程。
def on_message(self, msg):
IOLoop.current().spawn_callback(process_message, msg)
@gen.coroutine
def process_message(self, msg):
...
An important distinction here is that spawn_callback
detaches the coroutine from the code in WebSocketHandler
that receives messages: you may get a second on_message
call before the callback spawned in the first one has finished. 这里一个重要的区别是
spawn_callback
将协程从接收消息的WebSocketHandler
中的代码中分离出来:在第一个回调产生的回调完成之前,你可能会得到第二个on_message
调用。 Use the methods in the tornado.locks
and tornado.queues
modules to manage this concurrency. 使用
tornado.locks
和tornado.queues
模块中的方法来管理这种并发。 (By contrast, in RequestHandler.data_received
, which may be a coroutine, you won't get a second chunk of data until the second has been processed, and an uncaught exception will abort the connection) (相比之下,在
RequestHandler.data_received
, 可能是一个协程,在处理第二个数据之前,你不会获得第二个数据块,并且未捕获的异常将中止连接)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.