MarMan29
MarMan29

Reputation: 729

Tornado Error Handling

I want to be able to handle a nicer error that's displayed if i type an incorrect URL E.g. localhost:8000/AFDADSFDKFADS

I get an ugly python traceback message because a tornado.web.HTTPError exception is thrown. I know I can use a regex to catch all scenarios other than my proper URLs however I figure there must be a way to handle this error within Tornado.

I know that I can use the write_error() when extending the tornado.web.RequestHandler but because this error is happening in the tornado.web.Application class I don't know how to deal with it. I think it might have something to do with the class tornado.web.ErrorHandler(application, request, **kwargs) however I'm unsure.

Also can someone tell me if i'm in a tornado.web.RequestHandler method and perform a raise KeyError or other exception without catching it why the write_error() isn't invoked? It seems the exception is ignored.

Upvotes: 7

Views: 7792

Answers (1)

Ben Darnell
Ben Darnell

Reputation: 22134

To provide a custom 404 page make a handler that calls self.set_status(404) (in addition to producing whatever output you want) and set it as default_handler_class in the Application constructor keyword arguments.

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: it's an easy way to return a specified status code but it doesn't give you control of the output.

Upvotes: 15

Related Questions