1
Fork 0
mirror of https://github.com/allthingslinux/tux.git synced 2024-10-02 16:43:12 +00:00
tux/.archive/error_handler.py
kzndotsh 5e67bc6306 feat(ctx_error_handler.py): add new error handler for command context
refactor(error_handler.py): update error handling logic to improve error messages and logging
fix(error_handler.py): handle app command errors separately to avoid conflicts
style(error_handler.py): improve code readability and maintainability by simplifying error handling logic

feat(test_error_handler.py): add new file for testing error handling in discord.py
This new file contains a Cog class with commands to raise every type of discord.py error for testing purposes.

feat: add error handling commands to ErrorTests cog in discord bot

This commit adds a series of commands to the ErrorTests cog in the discord bot. Each command raises a specific exception when invoked, allowing for testing and debugging of error handling mechanisms. The exceptions covered include DisabledCommand, CommandInvokeError, CommandOnCooldown, MaxConcurrencyReached, various ExtensionErrors, ClientException, and CommandRegistrationError.

refactor(error_handler.py): rename ErrorHandler to UnifiedErrorHandler for clarity
feat(error_handler.py): add support for traditional command errors and app command errors
fix(error_handler.py): improve error message for better user experience
style(error_handler.py): refactor code for better readability and maintainability
2024-05-01 04:10:58 +00:00

98 lines
4.5 KiB
Python

import traceback
import discord
from discord import app_commands
from discord.ext import commands
from loguru import logger
# Custom error handling mappings and messages.
error_map = {
# app_commands
app_commands.AppCommandError: "An error occurred: {error}",
app_commands.CommandInvokeError: "A command invoke error occurred: {error}",
app_commands.TransformerError: "A transformer error occurred: {error}",
app_commands.MissingRole: "You are missing the role required to use this command.",
app_commands.MissingAnyRole: "You are missing some roles required to use this command.",
app_commands.MissingPermissions: "You are missing the required permissions to use this command.",
app_commands.CheckFailure: "You are not allowed to use this command.",
app_commands.CommandNotFound: "This command was not found.",
app_commands.CommandOnCooldown: "This command is on cooldown. Try again in {error.retry_after:.2f} seconds.",
app_commands.BotMissingPermissions: "The bot is missing the required permissions to use this command.",
app_commands.CommandSignatureMismatch: "The command signature does not match: {error}",
# commands
commands.CommandError: "An error occurred: {error}",
commands.CommandInvokeError: "A command invoke error occurred: {error}",
commands.ConversionError: "An error occurred during conversion: {error}",
commands.MissingRole: "You are missing the role required to use this command.",
commands.MissingAnyRole: "You are missing some roles required to use this command.",
commands.MissingPermissions: "You are missing the required permissions to use this command.",
commands.CheckFailure: "You are not allowed to use this command.",
commands.CommandNotFound: "This command was not found.",
commands.CommandOnCooldown: "This command is on cooldown. Try again in {error.retry_after:.2f} seconds.",
commands.BadArgument: "Invalid argument passed. Correct usage:\n```{ctx.command.usage}```",
commands.MissingRequiredArgument: "Missing required argument. Correct usage:\n```{ctx.command.usage}```",
commands.MissingRequiredAttachment: "Missing required attachment.",
commands.NotOwner: "You are not the owner of this bot.",
commands.BotMissingPermissions: "The bot is missing the required permissions to use this command.",
}
class ErrorHandler(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
self.error_message = "An error occurred. Please try again later."
bot.tree.error(self.dispatch_to_app_command_handler)
async def dispatch_to_app_command_handler(
self, interaction: discord.Interaction, error: app_commands.AppCommandError
):
"""Dispatch command error to app_command_error event."""
await self.on_app_command_error(interaction, error)
async def on_app_command_error(
self, interaction: discord.Interaction, error: app_commands.AppCommandError
):
"""Handle app command errors."""
error_message = error_map.get(type(error), self.error_message).format(error=error)
if interaction.response.is_done():
await interaction.followup.send(error_message, ephemeral=True)
else:
await interaction.response.send_message(error_message, ephemeral=True)
if type(error) not in error_map:
self.log_error_traceback(error)
@commands.Cog.listener()
async def on_command_error(
self, ctx: commands.Context[commands.Bot], error: commands.CommandError
):
"""Handle traditional command errors."""
if isinstance(
error,
commands.CommandNotFound
| commands.UnexpectedQuoteError
| commands.InvalidEndOfQuotedStringError
| commands.CheckFailure,
):
return # Ignore these specific errors.
error_message = error_map.get(type(error), self.error_message).format(error=error, ctx=ctx)
await ctx.send(
content=error_message,
ephemeral=False,
)
if type(error) not in error_map:
self.log_error_traceback(error)
def log_error_traceback(self, error: Exception):
"""Helper method to log error traceback."""
trace = traceback.format_exception(None, error, error.__traceback__)
formatted_trace = "".join(trace)
logger.error(f"Error: {error}\nTraceback:\n{formatted_trace}")
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(ErrorHandler(bot))