基于一些谷歌搜索,我安装了以下错误处理程序。然而,似乎返回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)
答案 0 :(得分:14)
首先,您在prepare
中加注的例外代码为200
,因此它未被get_error_html
函数捕获。
其次,不推荐使用get_error_html
:使用write_error
代替write_error)。
最后,您无需在__init__
上致电ErrorHandler
:使用initialize
(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()
答案 1 :(得分:11)
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!')
default_handler_class
和default_handler_args
settings = {
'default_handler_class': ErrorHandler,
'default_handler_args': dict(status_code=404)
}
application = tornado.web.Application([
(r"/", MainHandler)
], **settings)
结果。除了404之外的所有错误都将由BaseHandler处理。 404 - ErrorHandler。就是这样:))
答案 2 :(得分:-1)
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)