From 2b53d8dd3cbbdddb3b50b90dd9a6488aceba7c53 Mon Sep 17 00:00:00 2001 From: Teemu Rytilahti Date: Sat, 18 Feb 2023 15:56:29 +0100 Subject: [PATCH] Capture all exceptions from cli commands 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 4fd3990bc..3eed20320 100755 --- a/kasa/cli.py +++ b/kasa/cli.py @@ -31,7 +31,21 @@ 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",