Python龙卷风,在open()内部给出错误

时间:2014-08-04 19:15:29

标签: websocket tornado

我实现了龙卷风的Web套接字服务器(目前版本为3.1)。

open()函数内部,我检查GET参数,然后基于它 - 我想引发一个错误。

这样的事情:

def open(self):
   token = self.get_argument('token')
   if ...:
      ??? # raise an error

如何在open函数内引发错误?我没有找到办法做到这一点。

由于

1 个答案:

答案 0 :(得分:0)

你可以像往常一样提出异常:

class EchoWebSocket(websocket.WebSocketHandler):

    def open(self):
        if some_error:
            raise Exception("Some error occurred")

open中发生未处理的异常时,Tornado将中止连接。以下是open计划在龙卷风来源中运行的方式:

    self._run_callback(self.handler.open, *self.handler.open_args,
                       **self.handler.open_kwargs)

以下是_run_callback

def _run_callback(self, callback, *args, **kwargs):
    """Runs the given callback with exception handling.

    On error, aborts the websocket connection and returns False.
    """
    try:
        callback(*args, **kwargs)
    except Exception:
        app_log.error("Uncaught exception in %s",
                      self.request.path, exc_info=True)
        self._abort()

def _abort(self):
    """Instantly aborts the WebSocket connection by closing the socket"""
    self.client_terminated = True
    self.server_terminated = True
    self.stream.close()  # forcibly tear down the connection
    self.close()  # let the subclass cleanup

如您所见,它会在发生异常时中止连接。