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)
A Tornado web application generally consists of one or more RequestHandler subclasses, an Application object which routes incoming requests to handlers, and a main() function to start the server.
Exceptions to the RescueWhen an exception is thrown, the control flow of the program is interrupted. If no one handles the exception, it causes the program to crash. The user will see the exception's message, which they most likely won't understand. The message might not even be localized to their language.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With