diff --git a/tdp/cli/__main__.py b/tdp/cli/__main__.py index 9b5f14a7..ae0710bd 100644 --- a/tdp/cli/__main__.py +++ b/tdp/cli/__main__.py @@ -20,6 +20,7 @@ from tdp.cli.commands.validate import validate from tdp.cli.commands.vars import vars from tdp.cli.logger import setup_logging +from tdp.cli.utils import CatchGroup # Add `-h` shortcut to print the help for the whole cli. # Click only uses `--help` by default. @@ -35,7 +36,7 @@ def load_env(ctx: click.Context, param: click.Parameter, value: Path) -> Optiona logging.warning(f"Environment file {value} does not exist.") -@click.group("tdp", context_settings=CONTEXT_SETTINGS) +@click.group("tdp", context_settings=CONTEXT_SETTINGS, cls=CatchGroup) @click.option( "--env", default=".env", diff --git a/tdp/cli/utils.py b/tdp/cli/utils.py index af781fca..1d228141 100644 --- a/tdp/cli/utils.py +++ b/tdp/cli/utils.py @@ -217,3 +217,14 @@ def decorator(fn: FC) -> FC: return decorator else: return decorator(func) + + +class CatchGroup(click.Group): + """Catch exceptions and print them to stderr.""" + + def __call__(self, *args, **kwargs): + try: + return self.main(*args, **kwargs) + + except Exception as e: + print("Error:", e)