From 92636fe82db7c113983b0915f375cef09a8b09ad Mon Sep 17 00:00:00 2001 From: Teemu R Date: Sat, 18 Feb 2023 17:32:03 +0100 Subject: [PATCH] Pretty-print all exceptions from cli commands (#428) Print out the repr of captured exception instead of full traceback --- kasa/cli.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/kasa/cli.py b/kasa/cli.py index f72759a5..100821d9 100755 --- a/kasa/cli.py +++ b/kasa/cli.py @@ -52,7 +52,21 @@ click.anyio_backend = "asyncio" pass_dev = click.make_pass_decorator(SmartDevice) -@click.group(invoke_without_command=True) +class ExceptionHandlerGroup(click.Group): + """Group to capture all exceptions and print them nicely. + + Idea from https://stackoverflow.com/a/44347763 + """ + + def __call__(self, *args, **kwargs): + """Run the coroutine in the event loop and print any exceptions.""" + try: + asyncio.get_event_loop().run_until_complete(self.main(*args, **kwargs)) + except Exception as ex: + click.echo(f"Got error: {ex!r}") + + +@click.group(invoke_without_command=True, cls=ExceptionHandlerGroup) @click.option( "--host", envvar="KASA_HOST",