Tornado 错误处理 [英] Tornado Error Handling

查看:35
本文介绍了Tornado 错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够处理一个更好的错误,如果我输入了不正确的 URL E.g.本地主机:8000/AFDADSFDKFADS

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

因为抛出了 tornado.web.HTTPError 异常,我收到了一条丑陋的 python 回溯消息.我知道我可以使用正则表达式来捕获除正确 URL 之外的所有场景,但是我认为必须有一种方法可以在 Tornado 中处理此错误.

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.

我知道在扩展 tornado.web.RequestHandler 时我可以使用 write_error() 但因为这个错误发生在 tornado.web.Application 类不知道怎么处理.我认为它可能与 tornado.web.ErrorHandler(application, request, **kwargs) 类有关,但我不确定.

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.

也有人可以告诉我我是否在 tornado.web.RequestHandler 方法中并执行 raise KeyError 或其他异常而不捕获它为什么 write_error() 没有被调用?似乎忽略了异常.

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.

推荐答案

要提供自定义 404 页面,请制作一个调用 self.set_status(404) 的处理程序(除了生成您想要的任何输出) 并在 Application 构造函数关键字参数中将其设置为 default_handler_class.

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)

您可能不想使用 ErrorHandler:这是一种返回指定状态代码的简单方法,但它不能让您控制输出.

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.

这篇关于Tornado 错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆