Websocket error handling hook
WebSocketHandler doesn't currently have a good way of installing a class-wide handler for uncaught exceptions. The only way is to override _run_callback, but that's awkward (and the method is changing in Tornado 4.5 so naive overrides may break the ability to use coroutines). We should add an explicit error-handling hook.
The add_future call to f.result() also needs to be refactored so its exceptions can be handled in the same way instead of escaping to the IOLoop.
See https://stackoverflow.com/questions/42822958/tornado-websocket-handler-uncaught-exception/43017469#43017469
Hi Ben, I just tried the workaround you suggested in Stack Overflow and it doesn't seem to work. I also tried some variations with no luck. Maybe I'm missing something?
Here is my minimal working test:
from traceback import print_exc
from tornado.gen import coroutine
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.websocket import WebSocketHandler
class TestWSHandler(WebSocketHandler):
def _run_callback(self, f, *a, **kw):
def wrapper():
try:
f(*a, **kw)
except Exception:
print_exc()
return super()._run_callback(wrapper)
def check_origin(self, origin):
return True
@coroutine
def on_message(self, message):
raise Exception()
if __name__ == '__main__':
Application([('/ws', TestWSHandler)]).listen(8888)
IOLoop.current().start()
Ah, _run_callback is on WebSocketProtocol, not WebSocketHandler. That's very inconvenient to override. Additionally, the code I posted doesn't properly support coroutines as callbacks. It's probably better to just handle this at the application level until proper support can be added to the framework. Either wrap all your callbacks in a big try/except block or if you have enough of them that this gets irritating, you can make your own exception-catching decorator.
This module does not pass the test http://www.websocket.org/echo.html. Do you have an example site to test? Thank.
What do you mean this module does not pass that test? The module alone is just a framework. There is an example in https://github.com/tornadoweb/tornado/tree/master/demos/websocket.
In any case, this issue is not the place to discuss anything about the websocket module except its error handling. If you have any follow up questions, the mailing list is probably the best place for them.
Same issue here. Any news?
If you just want to log the error, you can override RequestHandler.log_exception since Tornado 5.1. For other kinds of error handling, I don't think anything has changed.