An attempt at better connection error-handling

This commit is contained in:
Tony Garnock-Jones 2020-07-22 10:06:58 +02:00
parent a4f5da1a25
commit 378e4b69a6
1 changed files with 17 additions and 12 deletions

View File

@ -549,6 +549,10 @@ class WebsocketConnection(Connection):
self.loop.create_task(self.ws.close()) self.loop.create_task(self.ws.close())
self.loop.call_soon_threadsafe(_do_disconnect) self.loop.call_soon_threadsafe(_do_disconnect)
def __connection_error(self, e):
log.error('%s: Could not connect to server: %s' % (self.__class__.__qualname__, e))
return False
async def main(self, loop, on_connected=None): async def main(self, loop, on_connected=None):
if self.ws is not None: if self.ws is not None:
raise Exception('Cannot run connection twice!') raise Exception('Cannot run connection twice!')
@ -556,19 +560,20 @@ class WebsocketConnection(Connection):
self.loop = loop self.loop = loop
try: try:
async with websockets.connect(self.url) as ws: self.ws = await websockets.connect(self.url)
if on_connected: await on_connected()
self.ws = ws
self._on_connected()
try:
while True:
chunk = await ws.recv()
self._on_event(protocol.Decoder(chunk).next())
except websockets.exceptions.ConnectionClosed:
pass
except OSError as e: except OSError as e:
log.error('%s: Could not connect to server: %s' % (self.__class__.__qualname__, e)) return self.__connection_error(e)
return False except websockets.exceptions.InvalidHandshake as e:
return self.__connection_error(e)
try:
if on_connected: await on_connected()
self._on_connected()
while True:
chunk = await self.ws.recv()
self._on_event(protocol.Decoder(chunk).next())
except websockets.exceptions.WebSocketException:
pass
finally: finally:
self._on_disconnected() self._on_disconnected()