问题描述
基于一些谷歌搜索,我安装了以下错误处理程序.然而,虽然 404 是,但似乎返回 http 500 的 python 异常并没有被这些东西困住.使用我在下面代码中留下的打印语句,我可以看到它没有命中任何这些例程.我真的应该做什么?
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)
推荐答案
首先,您在 prepare
中提出的异常具有代码 200
,因此它不是被 get_error_html
函数捕获.
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.
其次,get_error_html
已被弃用:使用 write_error
代替(write_error).
Secondly, get_error_html
is deprecated: use write_error
, instead (write_error).
最后,您不需要在 ErrorHandler
上调用 __init__
:使用 initialize
(initialize),但在这种情况下你不需要它.
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.
这是一个工作示例:
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()
这篇关于优雅地处理 Tornado 应用程序中的应用程序异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!