Tornado Error Handling

我的梦境 提交于 2019-12-07 06:07:28

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/30939298/tornado-error-handling

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!