diff mbox series

asyncrpc: Handle websockets exceptions

Message ID 20241230123547.2593913-1-philip.lorenz@bmw.de
State New
Headers show
Series asyncrpc: Handle websockets exceptions | expand

Commit Message

Philip Lorenz Dec. 30, 2024, 12:35 p.m. UTC
The websockets library throws a number of exceptions which are currently
not caught leading to unhandled exceptions in the idle loop.

Fix this by catching them and reexposing them as a `ConnectionError`
which is the exception expected by users of `asyncrpc`.

Signed-off-by: Philip Lorenz <philip.lorenz@bmw.de>
---
 lib/bb/asyncrpc/client.py | 15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)
diff mbox series

Patch

diff --git a/lib/bb/asyncrpc/client.py b/lib/bb/asyncrpc/client.py
index 9be49261c..17b72033b 100644
--- a/lib/bb/asyncrpc/client.py
+++ b/lib/bb/asyncrpc/client.py
@@ -112,11 +112,16 @@  class AsyncClient(object):
             )
 
         async def connect_sock():
-            websocket = await websockets.connect(
-                uri,
-                ping_interval=None,
-                open_timeout=self.timeout,
-            )
+            try:
+                websocket = await websockets.connect(
+                    uri,
+                    ping_interval=None,
+                    open_timeout=self.timeout,
+                )
+            except asyncio.exceptions.TimeoutError:
+                raise ConnectionError("Timeout while connecting to websocket")
+            except (OSError, websockets.InvalidHandshake, websockets.InvalidURI) as exc:
+                raise ConnectionError(f"Could not connect to websocket: {exc}") from exc
             return WebsocketConnection(websocket, self.timeout)
 
         self._connect_sock = connect_sock