Search code examples
pythonpython-3.xflaskerror-handlingflask-cli

Flask app.errorhandler not catching exceptions when running with Flask-CLI


I am struggling to get my Flask application to properly handle errors when invoking the application using Flask-CLI.

Here is a simple file called 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')

I invoke the test_run function via this bash command: FLASK_APP=app_runner.py flask test_run.

I see the first print statement 'You will see this', but I don't see the one that says 'I wish I saw this'.

I hit the Exception, but I never go into the code defined under app.errorhandler. Does anyone have any suggestions?


Solution

  • Error handlers are only for errors raised while handling views. CLI commands are totally separate. If you want to handle an error in a Click command, you need to handle it as you would any Python exception: with a try / except block.