在Tornado应用程序中优雅地处理应用程序异常

Kar*_*rra 11 tornado

基于一些谷歌搜索,我安装了以下错误处理程序.然而,似乎返回http 500的python异常并没有被这些东西所困,尽管404是.使用我在下面的代码中留下的打印语句,我可以看到它没有遇到任何这些例程.我该怎么办?

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)
Run Code Online (Sandbox Code Playgroud)

lbo*_*lla 14

首先,你提出的例外prepare有代码200,因此它没有被捕获到get_error_html函数中.

其次,get_error_html弃用:use write_error,而不是(write_error).

最后,你并不需要调用__init__ErrorHandler:初始化处理程序使用initialize(初始化),但在这种情况下,你不需要它.

这是一个工作示例:

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()
Run Code Online (Sandbox Code Playgroud)


chm*_*iuk 11

  1. 处理程序.让我们定义一些我们将要使用的默认处理程序
import tornado.web


class BaseHandler(tornado.web.RequestHandler):
    """
    Base handler gonna to be used instead of RequestHandler
    """
    def write_error(self, status_code, **kwargs):
        if status_code in [403, 404, 500, 503]:
            self.write('Error %s' % status_code)
        else:
            self.write('BOOM!')


class ErrorHandler(tornado.web.ErrorHandler, BaseHandler):
    """
    Default handler gonna to be used in case of 404 error
    """
    pass


class MainHandler(BaseHandler):
    """
    Main handler
    """
    def get(self):
        self.write('Hello world!')
Run Code Online (Sandbox Code Playgroud)
  1. 设置.我们需要定义default_handler_classdefault_handler_args以及
settings = {
    'default_handler_class': ErrorHandler,
    'default_handler_args': dict(status_code=404)
}
Run Code Online (Sandbox Code Playgroud)
  1. 应用.
application = tornado.web.Application([
    (r"/", MainHandler)
], **settings)
Run Code Online (Sandbox Code Playgroud)

结果.除了404之外的所有错误都将由BaseHandler处理.404 - ErrorHandler.而已 :)