Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tornado Error Handling

Tags:

tornado

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.

like image 952
MarMan29 Avatar asked Jun 19 '15 13:06

MarMan29


People also ask

What is Tornado web application?

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. A minimal “hello world” example looks something like this: import asyncio import tornado.web class MainHandler(tornado. web.

Is tornado asynchronous?

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.


1 Answers

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.

like image 140
Ben Darnell Avatar answered Nov 14 '22 00:11

Ben Darnell