Skip to content

Commit

Permalink
Better error handling when reading from the channel (#18)
Browse files Browse the repository at this point in the history
* Better error handling when readng from the channel

* Linter

* Remove timeout
  • Loading branch information
zhulik authored Aug 13, 2022
1 parent 134336f commit 0af43dc
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 13 deletions.
6 changes: 2 additions & 4 deletions aiotractive/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def __init__( # pylint: disable=too-many-arguments

if self.session is None:
loop = loop or asyncio.get_event_loop()
self.session = aiohttp.ClientSession()
self.session = aiohttp.ClientSession(raise_for_status=True)
self._close_session = True

self._user_credentials = None
Expand All @@ -57,7 +57,7 @@ async def request(self, *args, **kwargs):
"""Perform request with error wrapping."""
try:
return await self.raw_request(*args, **kwargs)
except aiohttp.client_exceptions.ClientResponseError as error:
except ClientResponseError as error:
if error.status in [401, 403]:
raise UnauthorizedError from error
if error.status == 404:
Expand All @@ -75,7 +75,6 @@ async def raw_request(self, uri, params=None, data=None, method="GET"):
headers=await self.auth_headers(),
timeout=self._timeout,
) as response:
response.raise_for_status()
if "Content-Type" in response.headers and "application/json" in response.headers["Content-Type"]:
return await response.json()
return await response.read()
Expand Down Expand Up @@ -103,7 +102,6 @@ async def authenticate(self):
headers=self.base_headers(),
timeout=self._timeout,
) as response:
response.raise_for_status()
if "Content-Type" in response.headers and "application/json" in response.headers["Content-Type"]:
self._user_credentials = await response.json()
self._auth_headers = {
Expand Down
32 changes: 24 additions & 8 deletions aiotractive/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import time
from asyncio.exceptions import TimeoutError as AIOTimeoutError

from .exceptions import DisconnectedError, TractiveError
from aiohttp.client_exceptions import ClientResponseError

from .exceptions import DisconnectedError, TractiveError, UnauthorizedError


class Channel:
Expand Down Expand Up @@ -32,9 +34,12 @@ async def listen(self):

if event["type"] == "error":
self._check_connection_task.cancel()

await self._check_connection_task
raise TractiveError() from event["error"]

self._listen_task.cancel()
await self._listen_task

raise event["error"]

if event["type"] == "cancelled":
self._listen_task.cancel()
Expand All @@ -46,9 +51,7 @@ async def _listen(self):
while True:
try:
async with self._api.session.request(
"POST",
self.CHANNEL_URL,
headers=await self._api.auth_headers(),
"POST", self.CHANNEL_URL, headers=await self._api.auth_headers()
) as response:
async for data, _ in response.content.iter_chunks():
event = json.loads(data)
Expand All @@ -60,12 +63,25 @@ async def _listen(self):
await self._queue.put({"type": "event", "event": event})
except AIOTimeoutError:
continue
except ClientResponseError as error:
try:
if error.status in [401, 403]:
raise UnauthorizedError from error
raise TractiveError from error
except TractiveError as error:
await self._queue.put({"type": "error", "error": error})
return

except asyncio.CancelledError as error:
await self._queue.put({"type": "cancelled", "error": error})
return

except Exception as error: # pylint: disable=broad-except
await self._queue.put({"type": "error", "error": error})
return
try:
raise TractiveError from error
except TractiveError as error:
await self._queue.put({"type": "error", "error": error})
return

async def _check_connection(self):
try:
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

setup(
name="aiotractive",
version="0.5.4",
version="0.5.5",
author="Gleb Sinyavskiy",
author_email="[email protected]",
description="Asynchronous Python client for the Tractive REST API",
Expand Down

0 comments on commit 0af43dc

Please sign in to comment.