当 运行 Flask-CLI 时,Flask app.errorhandler 未捕获异常
Flask app.errorhandler not catching exceptions when running with Flask-CLI
我正在努力让我的 Flask 应用程序在使用 Flask-CLI 调用应用程序时正确处理错误。
这是一个名为 app_runner.py
的简单文件:
import click
from flask import Flask
from flask_cli import FlaskCLI
app = Flask(__name__)
FlaskCLI(app)
@app.errorhandler(Exception)
def catch_error(e):
print('I wish I saw this')
@app.cli.command(with_appcontext=True)
def test_run():
with app.app_context():
print('You will see this')
raise Exception
print('You won\'t see this')
我通过这个 bash 命令调用 test_run
函数:FLASK_APP=app_runner.py flask test_run
.
我看到第一个打印语句 'You will see this',但我没有看到 'I wish I saw this'.
我点击了Exception
,但是我从来没有进入app.errorhandler
下定义的代码。有人有什么建议吗?
错误处理程序仅用于处理 视图 时出现的错误。 CLI 命令是完全独立的。如果你想处理 Click 命令中的错误,你需要像处理任何 Python 异常一样处理它:使用 try / except
块。
我正在努力让我的 Flask 应用程序在使用 Flask-CLI 调用应用程序时正确处理错误。
这是一个名为 app_runner.py
的简单文件:
import click
from flask import Flask
from flask_cli import FlaskCLI
app = Flask(__name__)
FlaskCLI(app)
@app.errorhandler(Exception)
def catch_error(e):
print('I wish I saw this')
@app.cli.command(with_appcontext=True)
def test_run():
with app.app_context():
print('You will see this')
raise Exception
print('You won\'t see this')
我通过这个 bash 命令调用 test_run
函数:FLASK_APP=app_runner.py flask test_run
.
我看到第一个打印语句 'You will see this',但我没有看到 'I wish I saw this'.
我点击了Exception
,但是我从来没有进入app.errorhandler
下定义的代码。有人有什么建议吗?
错误处理程序仅用于处理 视图 时出现的错误。 CLI 命令是完全独立的。如果你想处理 Click 命令中的错误,你需要像处理任何 Python 异常一样处理它:使用 try / except
块。