fix: Add robust error handling for cog loading - Add initialization timeout - Add proper cleanup on failure - Add teardown function - Add proper logging - Add proper cog removal order

This commit is contained in:
pacnpal
2024-11-15 01:04:25 +00:00
parent 888ed27d17
commit 484b0c0cb8

View File

@@ -1,23 +1,62 @@
"""VideoArchiver cog for Red-DiscordBot""" """VideoArchiver cog for Red-DiscordBot"""
from redbot.core.bot import Red from redbot.core.bot import Red
import asyncio
import logging
from .video_archiver import VideoArchiver from .video_archiver import VideoArchiver
from .exceptions import ProcessingError
logger = logging.getLogger("VideoArchiver")
async def setup(bot: Red) -> None: async def setup(bot: Red) -> None:
"""Load VideoArchiver.""" """Load VideoArchiver."""
# Load main cog first try:
cog = VideoArchiver(bot) # Load main cog first
await bot.add_cog(cog) cog = VideoArchiver(bot)
await bot.add_cog(cog)
# Wait for initialization to complete # Wait for initialization to complete with timeout
await cog.ready.wait() try:
await asyncio.wait_for(cog.ready.wait(), timeout=30)
except asyncio.TimeoutError:
logger.error("VideoArchiver initialization timed out")
await bot.remove_cog(cog.__class__.__name__)
raise ProcessingError("Initialization timed out")
# Only load commands if main cog initialized successfully # Only load commands if main cog initialized successfully
if cog.ready.is_set(): if cog.ready.is_set():
from .commands import VideoArchiverCommands try:
commands_cog = VideoArchiverCommands( from .commands import VideoArchiverCommands
bot, commands_cog = VideoArchiverCommands(
cog.config_manager, bot,
cog.update_checker, cog.config_manager,
cog.processor cog.update_checker,
) cog.processor
await bot.add_cog(commands_cog) )
await bot.add_cog(commands_cog)
except Exception as e:
logger.error(f"Failed to load commands cog: {str(e)}")
# Clean up main cog if commands fail to load
await bot.remove_cog(cog.__class__.__name__)
raise
else:
logger.error("VideoArchiver failed to initialize")
await bot.remove_cog(cog.__class__.__name__)
raise ProcessingError("Initialization failed")
except Exception as e:
logger.error(f"Failed to load VideoArchiver: {str(e)}")
raise
async def teardown(bot: Red) -> None:
"""Clean up when unloading."""
try:
# Remove commands cog first
if "VideoArchiverCommands" in bot.cogs:
await bot.remove_cog("VideoArchiverCommands")
# Then remove main cog
if "VideoArchiver" in bot.cogs:
await bot.remove_cog("VideoArchiver")
except Exception as e:
logger.error(f"Error during teardown: {str(e)}")
raise