捕获异常并显示自定义错误页面 [英] Catch an exception and displaying a custom error page

查看:351
本文介绍了捕获异常并显示自定义错误页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Flask应用。我在我的一个库中做了一个自定义异常,该异常与一个非常具体的错误有关,我想通知用户。

I have a Flask app. I made a custom exception in one of my libraries related to a very specific error that I would like to notify the user about.

我想发生的事情是将Flask转到此异常的默认页面,并简短说明用户需要执行的操作。

What I would like to happen is whenever this exception is thrown have Flask go to a default page for this exception with a short explanation of what the user needs to do.

我有

class SpecificException(Exceptions):
    pass

然后

def __verify_compatible_version(self):
    if self.version != VERSION:
        raise SpecificException ("detected incompatible version")

我不确定该怎么做。 文档似乎表明这是可能的,但我不知道没有看到任何好的例子,也没有建议如何做。我如何显示自定义页面来处理我的自定义异常?

I am not certain how to do that. The docs seem to make clear it is possible but I don't see any good examples nor advice for how to do it. How can I display a custom page to handle my custom exception?

推荐答案

您需要为该异常注册一个错误处理程序。错误处理程序的行为类似于普通视图,它应返回响应(或类似响应的数据)。在这种情况下,我假设您最终要发送500个状态代码,所以这就是为什么同时有,500 和退货的原因。处理程序将异常实例作为第一个参数,因此,如果模板具有特殊信息,则可以在呈现模板时使用它。

You need to register an error handler for the exception. The error handler behaves like a normal view, it should return a response (or response-like data). In this case, I'm assuming you want to ultimately send a 500 status code, so that's why there's a , 500 along with the return. The handler receives the exception instance as the first argument, so you can use that when rendering a template if it has special information.

class SpecificException(Exception):
    pass

@app.errorhandler(SpecificException)
def handle_specific_exception(e):
    return render_template('errors/specific_exception.html', e=e), 500

这篇关于捕获异常并显示自定义错误页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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