Gracefully handling application exceptions in a Tornado application

Karra picture Karra · Jul 9, 2012 · Viewed 12k times · Source

Based on some googling I installed the following error handler. However the python exceptions which appear to return a http 500 are not trapped by this stuff, although 404's are. With the print statements I have left in the code below, I can see that it does not hit any of these routines. What should I really be doing?

class ErrorHandler(tornado.web.RequestHandler):
"""Generates an error response with status_code for all requests."""
def __init__ (self, application, request, status_code):
    print 'In ErrorHandler init'
    tornado.web.RequestHandler.__init__(self, application, request)
    self.set_status(status_code)

def get_error_html (self, status_code, **kwargs):
    print 'In get_error_html. status_code: ', status_code
    if status_code in [403, 404, 500, 503]:
        filename = '%d.html' % status_code
        print 'rendering filename: ', filename
        return self.render_string(filename, title=config.get_title())

    return "<html><title>%(code)d: %(message)s</title>" \
            "<body class='bodyErrorPage'>%(code)d: %(message)s</body>"\
            "</html>" % {
            "code": status_code,
            "message": httplib.responses[status_code],
            }

def prepare (self):
    print 'In prepare...'
    raise tornado.web.HTTPError(self._status_code)

Answer

lbolla picture lbolla · Jul 9, 2012

First of all, the exception that you are raising in prepare has code 200, therefore it's not caught in the get_error_html function.

Secondly, get_error_html is deprecated: use write_error, instead (write_error).

Finally, you don't need to call __init__ on ErrorHandler: to initialize a handler use initialize (initialize), but in this case you don't need it.

Here is a working example:

import tornado
import tornado.web


class ErrorHandler(tornado.web.RequestHandler):
    """Generates an error response with status_code for all requests."""

    def write_error(self, status_code, **kwargs):
        print 'In get_error_html. status_code: ', status_code
        if status_code in [403, 404, 500, 503]:
            self.write('Error %s' % status_code)
        else:
            self.write('BOOM!')

    def prepare(self):
        print 'In prepare...'
        raise Exception('Error!')


application = tornado.web.Application([
        (r"/", ErrorHandler),
        ])

if __name__ == "__main__":
    application.listen(8899)
    tornado.ioloop.IOLoop.instance().start()