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”的处理程序
在调试模式下运行。相反,交互式调试器将是
显示。
这表明,如果我们在调试模式 (debug=True) 下运行应用程序,@app.errorhandler(500) 将不会捕获 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 }}
输出:
参考资料:
- Flask Official documentation on error handling