Tornado Error Handling

I want to be able to handle a nicer error that appears if I find the wrong URL E.g. localhost:8000/AFDADSFDKFADS

I get an ugly python trace message because a tornado.web.HTTPError exception is thrown. I know that I can use regex to catch all scripts other than my correct URLs, however I believe there should be a way to handle this error in Tornado.

I know that with the extension tornado.web.RequestHandlerI can use write_error(), but since this error occurs in the class tornado.web.Application, I do not know how to deal with it. I think this may have something to do with the class tornado.web.ErrorHandler(application, request, **kwargs), however I'm not sure.

Also can someone tell me if I have a method tornado.web.RequestHandlerand execute raise KeyErroror another exception without catching it, why is write_error()not it called? The exception seems to be ignored.

+4
source share
1 answer

To create a custom 404 page, create a handler that calls self.set_status(404)(in addition to creating the desired result) and set it as default_handler_classin the constructor keyword arguments Application.

class My404Handler(RequestHandler):
    # Override prepare() instead of get() to cover all possible HTTP methods.
    def prepare(self):
        self.set_status(404)
        self.render("404.html")

app = Application(..., default_handler_class=My404Handler)

You probably don't want to use ErrorHandler: this is an easy way to return the specified status code, but it does not give you control over the exit.

+9
source

All Articles