From b05d9bca2dd56f00fb7bbd1df59936ff2e9cdca2 Mon Sep 17 00:00:00 2001 From: DevilXD Date: Fri, 11 Feb 2022 16:50:32 +0100 Subject: [PATCH] Ensure connection error cause is included --- twitch.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/twitch.py b/twitch.py index e9e1643..6dd04fc 100644 --- a/twitch.py +++ b/twitch.py @@ -736,24 +736,29 @@ class Twitch: @asynccontextmanager async def request( - self, method: str, url: str, **kwargs + self, method: str, url: str, *, attempts: int = 5, **kwargs ) -> AsyncIterator[aiohttp.ClientResponse]: if self._session is None: await self.initialize() session = self._session assert session is not None - for attempt in range(5): + method = method.upper() + cause: Optional[Exception] = None + for attempt in range(attempts): + logger.debug(f"Request: ({method=}, {url=}, {attempts=}, {kwargs=})") try: async with session.request(method, url, **kwargs) as response: + logger.debug(f"Response: {response.status}: {response}") yield response - break - except (aiohttp.ClientConnectionError, aiohttp.ServerTimeoutError): - await asyncio.sleep(0.1 * attempt) - else: - raise RequestException( - "Ran out of attempts while handling a request: " - f"(method={method.upper()}, {url=}, {kwargs=})" - ) + return + except aiohttp.ClientConnectionError as exc: + cause = exc + if attempt < attempts - 1: + await asyncio.sleep(0.1 * attempt) + raise RequestException( + "Ran out of attempts while handling a request: " + f"({method=}, {url=}, {attempts=}, {kwargs=})" + ) from cause async def gql_request(self, op: GQLOperation) -> JsonType: headers = {