From e72a8b9a5c6cade5fe5694c4d8037198824aa7e4 Mon Sep 17 00:00:00 2001 From: Valerie Date: Fri, 23 May 2025 06:18:47 -0400 Subject: [PATCH] Improve error handling in ModrinthTracker API requests by adding session management and detailed logging for connection issues. Enhance user feedback for network errors and timeouts in the add command. --- modrinthtracker/modrinthtracker.py | 38 ++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/modrinthtracker/modrinthtracker.py b/modrinthtracker/modrinthtracker.py index c1c200f..ff66083 100644 --- a/modrinthtracker/modrinthtracker.py +++ b/modrinthtracker/modrinthtracker.py @@ -57,12 +57,29 @@ class ModrinthTracker(commands.Cog): async def _make_request(self, url, params=None): """Make a rate-limited request to the Modrinth API""" await self._rate_limit() - async with self.session.get(url, params=params) as response: - if response.status == 429: # Too Many Requests - retry_after = int(response.headers.get('Retry-After', 60)) - await asyncio.sleep(retry_after) - return await self._make_request(url, params) - return response + + # Ensure session is available + if self.session is None or self.session.closed: + self.session = aiohttp.ClientSession() + + try: + async with self.session.get(url, params=params) as response: + if response.status == 429: # Too Many Requests + retry_after = int(response.headers.get('Retry-After', 60)) + await asyncio.sleep(retry_after) + return await self._make_request(url, params) + return response + except aiohttp.ClientConnectorError: + # Connection error, try to recreate session and retry once + if self.session and not self.session.closed: + await self.session.close() + self.session = aiohttp.ClientSession() + async with self.session.get(url, params=params) as response: + return response + except Exception as e: + # Log the error for debugging + self.bot.logger.error(f"Error in _make_request: {str(e)}", exc_info=True) + raise @commands.group() @checks.admin() @@ -150,8 +167,15 @@ class ModrinthTracker(commands.Cog): else: await channel.send("No version information is currently available for this project.") + except aiohttp.ClientConnectorError: + await ctx.send("Error: Failed to connect to Modrinth API. Please try again in a few moments.") + except aiohttp.ClientError as e: + await ctx.send(f"Error: Network error occurred while contacting Modrinth API: {str(e)}") + except asyncio.TimeoutError: + await ctx.send("Error: Request to Modrinth API timed out. Please try again.") except Exception as e: - await ctx.send(f"An error occurred while adding the project: {str(e)}") + self.bot.logger.error(f"Error in modrinth add command: {str(e)}", exc_info=True) + await ctx.send(f"An unexpected error occurred. Please try again later or contact the bot owner if the issue persists.") @modrinth.command() async def remove(self, ctx, project_id: str):