Flask app.errorhandler在使用Flask-CLI运行时没有捕获异常

时间:2017-09-22 02:04:48

标签: python python-3.x flask error-handling flask-cli

在使用Flask-CLI调用应用程序时,我很难让我的Flask应用程序正确处理错误。

这是一个名为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

我看到第一个印刷声明'你会看到这个',但我没有看到那个说“我希望我看到这个”的声明。

我点击Exception,但我从未进入app.errorhandler下定义的代码。有没有人有任何建议?

1 个答案:

答案 0 :(得分:1)

错误处理程序仅用于处理视图时引发的错误。 CLI命令是完全独立的。如果要在Click命令中处理错误,则需要像处理任何Python异常一样处理它:使用try / except块。