Search code examples
pythonwebtornado

How to set up custom unhandled exception handler in Tornado?


I'm trying to implement custom unhandled request exception logging with overriding of the tornado.web.Application._handle_request_exception method:

def _handle_request_exception(self, e):
    logging.error('error')  # Just for test.

But I see the same log output like:

2012-09-01 03:35:09,947 [7399] root ERROR: Uncaught exception GET / (127.0.0.1)
HTTPRequest(...)
Traceback (most recent call last):

instead of my custom message. What am I doing wrong?


Solution

  • Well, first of all, the _handle_request_exception method is in RequestHandler, not Application.

    Secondly, you can't override a bound method with a new definition in the main namespace:

    def _handle_request_exception(self, e):
        logging.error('error')
    

    You need to subclass the RequestHandler class:

    class BaseHandler(tornado.web.RequestHandler):
        def _handle_request_exception(self, e):
            logging.error('error')
    

    all of your handlers should then inherit from BaseHandler.