Gracefully handling application exceptions in a To

2020-05-27 02:10发布

问题:

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)

回答1:

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()


回答2:

  1. Handlers. Lets define some default handlers we gonna to use
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!')
  1. Settings. We need to define default_handler_class and default_handler_args as well
settings = {
    'default_handler_class': ErrorHandler,
    'default_handler_args': dict(status_code=404)
}
  1. Application.
application = tornado.web.Application([
    (r"/", MainHandler)
], **settings)

as result. all errors except 404 gonna be handled by BaseHandler. 404 - ErrorHandler. that's it :)



回答3:

import tornado.web


class BaseHandler(tornado.web.RequestHandler):
    def write_error(self, status_code, **kwargs):
        print status_code
        super(BaseHandler, self).write_error(status_code, **kwargs)


标签: tornado