Improve exception handling and logging.
authorBenjamin Braatz <bb@bbraatz.eu>
Fri, 28 Jul 2023 09:47:17 +0000 (11:47 +0200)
committerBenjamin Braatz <bb@bbraatz.eu>
Fri, 28 Jul 2023 09:47:17 +0000 (11:47 +0200)
controlpi_plugins/wsclient.py

index 9ace98fc88e0185fb21feed9a9210333fa39b7c1..fd81680cb3517122fa371b5a9f6299bcd0dbce55 100644 (file)
@@ -1,11 +1,10 @@
 """Provide a client ControlPi plugin WSClient for websockets."""
 import asyncio
-import asyncio.exceptions
 import fcntl
 import json
 import socket
 import struct
-from websockets.exceptions import ConnectionClosed, InvalidMessage
+from websockets.exceptions import ConnectionClosed
 from websockets.client import connect, WebSocketClientProtocol
 
 from controlpi import BasePlugin, Message, MessageTemplate, BusException
@@ -197,6 +196,8 @@ class WSClient(BasePlugin):
         """Connect to wsserver and process messages from it."""
         async for websocket in connect(self.conf['url'],
                                        ping_interval=1, ping_timeout=5):
+            print(f"WSClient '{self.name}': Connection opened"
+                  f" to {self.conf['url']}.")
             await self.bus.send(Message(self.name,
                                         {'event':
                                          'connection opened'}))
@@ -229,9 +230,8 @@ class WSClient(BasePlugin):
                 await self.bus.send(Message(self.name,
                                             {'event':
                                              'connection closed'}))
-            except (OSError, InvalidMessage,
-                    asyncio.exceptions.TimeoutError) as e:
-                print(f"WSClient to {self.conf['url']} connection: {e}")
+            except Exception as e:
+                print(f"WSClient '{self.name}': Exception in connection: {e}")
             await asyncio.sleep(1)
 
     async def _send(self, json_message: str) -> None:
@@ -242,4 +242,4 @@ class WSClient(BasePlugin):
             try:
                 await self.bus.send(Message(self.name, translated_message))
             except BusException as e:
-                print(f"WSClient to {self.conf['url']} local bus: {e}")
+                print(f"WSClient '{self.name}': Exception on local bus: {e}")