Search code examples
python-3.xtornado

how to silence all exceptions in python tornado


I have a simple tornado app

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world".s())

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ], debug=False)

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

of course hitting http://127.0.0.1:8888 will result in a long exception in my terminal like this

ERROR:tornado.application:Uncaught exception GET / (127.0.0.1)
 HTTPServerRequest(protocol='http', host='127.0.0.1:8888', method='GET', uri='/', version='HTTP/1.1', remote_ip='127.0.0.1', headers={'Host': '127.0.0.1:8888', 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'en-US,en;q=0.8'})
Traceback (most recent call last):
  File "/Users/lib/python3.6/site- packages/tornado/web.py", line 1467, in _execute
    result = method(*self.path_args, **self.path_kwargs)
  File "test.py", line 6, in get
    self.write("Hello, world".s())
AttributeError: 'str' object has no attribute 's'
ERROR:tornado.access:500 GET / (127.0.0.1) 3.08ms

my question is how do I prevent uncaught exceptions' tracebacks and error messages from being printed to the stderr? I tried the sys.excepthook but it didint work with tornado for unknown reasons to me.

I am working with python 3.6 and tornado 4.4.2


Solution

  • found it here log_exception method

    By overriding the log_exception method you get to do whatever you want with that exception. In my case I only needed to pass just like this

    class MainHandler(tornado.web.RequestHandler):
        def log_exception(self, typ, value, tb):
            pass
    
        def get(self):
            self.write("Hello, world".s())