如何为Jinja Undefined错误创建自定义终结点?

时间:2019-04-07 15:26:50

标签: python flask error-handling jinja2

我不知道为什么,但是我的404错误处理程序没有警告,并且我的Web应用程序将任何页面视为现有页面,是什么导致它抛出jinja2.exceptions.UndefinedError而不是正常的404错误。

如何为jinja2.exceptions.UndefinedError设置错误处理程序?

我已经尝试制作404个端点,但是似乎没有一个起作用。

1 个答案:

答案 0 :(得分:0)

jinja2.exceptions.UndefinedError返回HTTP 500错误:

Failed to load resource: the server responded with a status of 500 (INTERNAL SERVER ERROR)

根据Flask文档(参考资料1):

  

在以下情况下将不使用“ 500 Internal Server Error”的处理程序   在调试模式下运行。相反,交互式调试器将是   显示。

这表明,如果我们在调试模式(@app.errorhandler(500))下运行应用程序,则debug=True将不会捕获HTTP 500错误处理程序或内部服务器错误。

这是一个有关在调试模式为false时如何使用自定义错误处理程序捕获jinja2.exceptions.UndefinedError的示例。

app.py

from flask import Flask, render_template


app = Flask(__name__)

@app.errorhandler(500)
def internal_server_error(e):
    return render_template('custom_error_handler.html', error_code=500), 500

@app.errorhandler(404)
def page_not_found(e):
    return render_template('custom_error_handler.html', error_code=404), 404    

@app.route('/', methods = ['GET'])
def home():
    return render_template("home.html")

if __name__ == '__main__':
    app.run(debug=False)

home.html

<html>
    <head>
        <title>Home</title>
    </head>
    <body>
        <h1>Data</h1>
        {{ data+student }}
    </body>
</html>

custom_error_handler.html

<h3>Custom Error Page</h3>
{{ error_code }}

输出:

  • 处理500个错误

    handling 500 error

  • 处理404错误

    Handling 404 error

参考:

  1. Flask Official documentation on error handling
相关问题