0

在使用 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')

test_run我通过这个 bash 命令调用该函数: FLASK_APP=app_runner.py flask test_run.

我看到第一个打印语句“你会看到这个”,但我没有看到那个说“我希望我看到这个”的语句。

我点击了Exception,但我从来没有进入下定义的代码app.errorhandler。有没有人有什么建议?

4

1 回答 1

3

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

于 2017-09-22T02:52:06.627 回答