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.
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.
Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.
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.
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