Skip to content

Commit 25ea9f7

Browse files
committed
Handle websocket error gracefully
1 parent 09efac2 commit 25ea9f7

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

template/server/messaging.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
)
1313
from pydantic import StrictStr
1414
from websockets.client import WebSocketClientProtocol, connect
15+
from websockets.exceptions import ConnectionClosedError, WebSocketException
1516

1617
from api.models.error import Error
1718
from api.models.logs import Stdout, Stderr
@@ -275,7 +276,8 @@ async def execute(
275276
access_token: str,
276277
):
277278
message_id = str(uuid.uuid4())
278-
self._executions[message_id] = Execution()
279+
execution = Execution()
280+
self._executions[message_id] = execution
279281

280282
if self._ws is None:
281283
raise Exception("WebSocket not connected")
@@ -319,7 +321,30 @@ async def execute(
319321
request = self._get_execute_request(message_id, complete_code, False)
320322

321323
# Send the code for execution
322-
await self._ws.send(request)
324+
try:
325+
await self._ws.send(request)
326+
except (ConnectionClosedError, WebSocketException) as e:
327+
logger.error(f"Failed to send execution request: {e}")
328+
await execution.queue.put(
329+
Error(
330+
name="WebSocketError",
331+
value="Failed to send execution request due to connection error",
332+
traceback=str(e),
333+
)
334+
)
335+
await execution.queue.put(UnexpectedEndOfExecution())
336+
return
337+
except:
338+
logger.error("Failed to send execution request due to unknown error")
339+
await execution.queue.put(
340+
Error(
341+
name="WebSocketError",
342+
value="Failed to send execution request due to unknown error",
343+
traceback="",
344+
)
345+
)
346+
await execution.queue.put(UnexpectedEndOfExecution())
347+
return
323348

324349
# Stream the results
325350
async for item in self._wait_for_result(message_id):

0 commit comments

Comments
 (0)