Skip to content
This repository was archived by the owner on Aug 21, 2025. It is now read-only.

Commit f978d39

Browse files
authored
fix: Do not supress callback exceptions (#332)
* feat: do not supress callback exceptions raised from calling callbacks * fix: add explicit clauses for ConnectionClosedOK in send and heartbeat * fix: change import order * fix: apply ruff format
1 parent c5e10d6 commit f978d39

File tree

2 files changed

+22
-20
lines changed

2 files changed

+22
-20
lines changed

realtime/_async/client.py

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from websockets import connect
1111
from websockets.client import ClientProtocol
1212

13+
from ..exceptions import NotConnectedError
1314
from ..message import Message
1415
from ..transformers import http_endpoint_url
1516
from ..types import (
@@ -92,7 +93,7 @@ async def _listen(self) -> None:
9293
"""
9394

9495
if not self._ws_connection:
95-
raise Exception("WebSocket connection not established")
96+
raise NotConnectedError("_listen")
9697

9798
try:
9899
async for msg in self._ws_connection:
@@ -103,7 +104,7 @@ async def _listen(self) -> None:
103104

104105
if channel:
105106
channel._trigger(msg.event, msg.payload, msg.ref)
106-
except Exception as e:
107+
except websockets.exceptions.ConnectionClosedError as e:
107108
await self._on_connect_error(e)
108109

109110
async def _reconnect(self) -> None:
@@ -186,19 +187,18 @@ async def _on_connect(self) -> None:
186187
self._heartbeat_task = asyncio.create_task(self._heartbeat())
187188
await self._flush_send_buffer()
188189

189-
async def _on_connect_error(self, e: Exception) -> None:
190-
if isinstance(e, websockets.exceptions.ConnectionClosedError):
191-
logger.error(
192-
f"WebSocket connection closed with code: {e.code}, reason: {e.reason}"
193-
)
190+
async def _on_connect_error(
191+
self, e: websockets.exceptions.ConnectionClosedError
192+
) -> None:
193+
logger.error(
194+
f"WebSocket connection closed with code: {e.code}, reason: {e.reason}"
195+
)
194196

195-
if self.auto_reconnect:
196-
logger.info("Initiating auto-reconnect sequence...")
197-
await self._reconnect()
198-
else:
199-
logger.error("Auto-reconnect disabled, terminating connection")
197+
if self.auto_reconnect:
198+
logger.info("Initiating auto-reconnect sequence...")
199+
await self._reconnect()
200200
else:
201-
logger.error(f"Error on connect: {e}")
201+
logger.error("Auto-reconnect disabled, terminating connection")
202202

203203
async def _flush_send_buffer(self):
204204
if self.is_connected and len(self.send_buffer) > 0:
@@ -232,7 +232,7 @@ async def close(self) -> None:
232232

233233
async def _heartbeat(self) -> None:
234234
if not self._ws_connection:
235-
raise Exception("WebSocket connection not established")
235+
raise NotConnectedError("_heartbeat")
236236

237237
while self.is_connected:
238238
try:
@@ -245,8 +245,10 @@ async def _heartbeat(self) -> None:
245245
await self.send(data)
246246
await asyncio.sleep(max(self.hb_interval, 15))
247247

248-
except Exception as e:
248+
except websockets.exceptions.ConnectionClosedError as e:
249249
await self._on_connect_error(e)
250+
except websockets.exceptions.ConnectionClosedOK as e:
251+
pass
250252

251253
def channel(
252254
self, topic: str, params: Optional[RealtimeChannelOptions] = None
@@ -344,14 +346,14 @@ async def send(self, message: Dict[str, Any]) -> None:
344346

345347
async def send_message():
346348
if not self._ws_connection:
347-
raise Exception(
348-
"WebSocket connection not established, a connection is expected to be established before sending a message"
349-
)
349+
raise NotConnectedError("_send")
350350

351351
try:
352352
await self._ws_connection.send(message)
353-
except Exception as e:
353+
except websockets.exceptions.ConnectionClosedError as e:
354354
await self._on_connect_error(e)
355+
except websockets.exceptions.ConnectionClosedOK:
356+
pass
355357

356358
if self.is_connected:
357359
await send_message()

realtime/exceptions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ def __init__(self, func_name: str):
77
self.offending_func_name: str = func_name
88

99
def __str__(self):
10-
return f"A WS connection has not been established. Ensure you call RealtimeClient.connect() before calling RealtimeClient.{self.offending_func_name}()"
10+
return f"A WS connection has not been established. Ensure you call AsyncRealtimeClient.connect() before calling AsyncRealtimeClient.{self.offending_func_name}()"
1111

1212

1313
class AuthorizationError(Exception):

0 commit comments

Comments
 (0)