Skip to main content

Exception Hierarchy

All Pycord exceptions inherit from DiscordException, which itself inherits from Python’s built-in Exception class.
Exception (built-in)
└── DiscordException
    ├── ClientException
    │   ├── InvalidData
    │   ├── InvalidArgument
    │   ├── LoginFailure
    │   ├── ConnectionClosed
    │   ├── PrivilegedIntentsRequired
    │   └── InteractionResponded
    ├── GatewayNotFound
    ├── ValidationError
    ├── HTTPException
    │   ├── Forbidden
    │   ├── NotFound
    │   └── DiscordServerError
    ├── ExtensionError
    │   ├── ExtensionAlreadyLoaded
    │   ├── ExtensionNotLoaded
    │   ├── NoEntryPointError
    │   ├── ExtensionFailed
    │   └── ExtensionNotFound
    └── ApplicationCommandError
        ├── CheckFailure
        └── ApplicationCommandInvokeError

Base Exceptions

Base exception class for Pycord.Ideally speaking, this could be caught to handle any exceptions raised from this library.
try:
    await some_discord_operation()
except discord.DiscordException as e:
    print(f"A Discord error occurred: {e}")
Exception that’s raised when an operation in the Client fails.These are usually for exceptions that happened due to user input.Inherits from: DiscordException
try:
    voice_client.play(source)
except discord.ClientException as e:
    print(f"Cannot play audio: {e}")

HTTP Exceptions

Exception that’s raised when an HTTP request operation fails.Attributes:
  • response (aiohttp.ClientResponse) - The response of the failed HTTP request
  • text (str) - The text of the error. Could be an empty string
  • status (int) - The status code of the HTTP request
  • code (int) - The Discord specific error code for the failure
Inherits from: DiscordException
try:
    await channel.send("Hello!")
except discord.HTTPException as e:
    print(f"HTTP {e.status}: {e.text}")
Exception that’s raised for when status code 403 occurs.Subclass of: HTTPExceptionThis typically means the bot lacks permissions to perform the action.
try:
    await member.ban()
except discord.Forbidden:
    print("I don't have permission to ban this member")
Exception that’s raised for when status code 404 occurs.Subclass of: HTTPExceptionThis means the resource you’re trying to access doesn’t exist.
try:
    message = await channel.fetch_message(12345)
except discord.NotFound:
    print("Message not found")
Exception that’s raised for when a 500 range status code occurs.Subclass of: HTTPExceptionThis indicates an error on Discord’s end.
try:
    await channel.send("Hello!")
except discord.DiscordServerError:
    print("Discord is having issues")

Client Exceptions

Exception that’s raised when the library encounters unknown or invalid data from Discord.Inherits from: ClientException
try:
    # Some operation that might receive invalid data
    pass
except discord.InvalidData:
    print("Received invalid data from Discord")
Exception that’s raised when an argument to a function is invalid some way (e.g. wrong value or wrong type).This could be considered the parallel of ValueError and TypeError except inherited from ClientException and thus DiscordException.Inherits from: ClientException
try:
    await guild.create_role(name="Test", colour="invalid")
except discord.InvalidArgument as e:
    print(f"Invalid argument: {e}")
Exception that’s raised when the Client.login() function fails to log you in from improper credentials or some other misc. failure.Inherits from: ClientException
try:
    await client.login('invalid_token')
except discord.LoginFailure:
    print("Failed to login with provided token")
Exception that’s raised when the gateway connection is closed for reasons that could not be handled internally.Attributes:
  • code (int) - The close code of the websocket
  • reason (str) - The reason provided for the closure
  • shard_id (Optional[int]) - The shard ID that got closed if applicable
Inherits from: ClientException
try:
    await client.connect()
except discord.ConnectionClosed as e:
    print(f"Connection closed with code {e.code}: {e.reason}")
Exception that’s raised when the gateway is requesting privileged intents, but they’re not ticked in the developer page yet.Go to https://discord.com/developers/applications/ and enable the intents that are required. Currently, these are:
  • Intents.members
  • Intents.presences
  • Intents.message_content
Attributes:
  • shard_id (Optional[int]) - The shard ID that got closed if applicable
Inherits from: ClientException
try:
    await client.start(token)
except discord.PrivilegedIntentsRequired:
    print("You need to enable privileged intents in the developer portal")
Exception that’s raised when sending another interaction response using InteractionResponse when one has already been done before.An interaction can only respond once.Attributes:
  • interaction (Interaction) - The interaction that’s already been responded to
Inherits from: ClientException
try:
    await interaction.response.send_message("First response")
    await interaction.response.send_message("Second response")  # This raises
except discord.InteractionResponded:
    await interaction.followup.send("Use followup instead!")
Exception that is raised when an async iteration operation has no more items.Inherits from: DiscordException
try:
    message = await history.next()
except discord.NoMoreItems:
    print("No more messages in history")
An exception that is raised when the gateway for Discord could not be found.Inherits from: DiscordException
try:
    await client.connect()
except discord.GatewayNotFound:
    print("Could not find Discord gateway")
An Exception that is raised when there is a Validation Error.Inherits from: DiscordException

Extension Exceptions

Base exception for extension related errors.Attributes:
  • name (str) - The extension that had an error
Inherits from: DiscordException
try:
    bot.load_extension('my_extension')
except discord.ExtensionError as e:
    print(f"Error with extension {e.name}")
An exception raised when an extension has already been loaded.Inherits from: ExtensionError
try:
    bot.load_extension('my_extension')
    bot.load_extension('my_extension')  # This raises
except discord.ExtensionAlreadyLoaded as e:
    print(f"{e.name} is already loaded")
An exception raised when an extension was not loaded.Inherits from: ExtensionError
try:
    bot.unload_extension('my_extension')
except discord.ExtensionNotLoaded as e:
    print(f"{e.name} is not loaded")
An exception raised when an extension does not have a setup entry point function.Inherits from: ExtensionError
# my_extension.py - missing setup function

try:
    bot.load_extension('my_extension')
except discord.NoEntryPointError:
    print("Extension missing setup() function")
An exception raised when an extension failed to load during execution of the module or setup entry point.Attributes:
  • name (str) - The extension that had the error
  • original (Exception) - The original exception that was raised. You can also get this via the __cause__ attribute
Inherits from: ExtensionError
try:
    bot.load_extension('my_extension')
except discord.ExtensionFailed as e:
    print(f"{e.name} failed to load: {e.original}")
An exception raised when an extension is not found.Attributes:
  • name (str) - The extension that had the error
Inherits from: ExtensionError
try:
    bot.load_extension('nonexistent_extension')
except discord.ExtensionNotFound as e:
    print(f"Could not find extension: {e.name}")

Application Command Exceptions

The base exception type for all application command related errors.This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from Bot, on_command_error.Inherits from: DiscordException
@bot.event
async def on_application_command_error(ctx, error):
    if isinstance(error, discord.ApplicationCommandError):
        await ctx.respond(f"An error occurred: {error}")
Exception raised when the predicates in Command.checks have failed.Inherits from: ApplicationCommandError
@bot.slash_command()
@commands.has_permissions(administrator=True)
async def admin_only(ctx):
    await ctx.respond("Admin command")

@bot.event
async def on_application_command_error(ctx, error):
    if isinstance(error, discord.CheckFailure):
        await ctx.respond("You don't have permission to use this command")
Exception raised when the command being invoked raised an exception.Attributes:
  • original (Exception) - The original exception that was raised. You can also get this via the __cause__ attribute
Inherits from: ApplicationCommandError
@bot.event
async def on_application_command_error(ctx, error):
    if isinstance(error, discord.ApplicationCommandInvokeError):
        print(f"Command raised: {error.original}")
        await ctx.respond("An error occurred while executing the command")

Exception Handling Best Practices

Catching Specific Exceptions

Always catch the most specific exception first:
try:
    await member.ban(reason="Spamming")
except discord.Forbidden:
    await ctx.respond("I don't have permission to ban members")
except discord.HTTPException as e:
    await ctx.respond(f"Failed to ban: {e}")

Catching All Discord Exceptions

To catch all Pycord exceptions:
try:
    await some_discord_operation()
except discord.DiscordException as e:
    print(f"A Discord error occurred: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

Error Event Handlers

Use event handlers for global error handling:
@bot.event
async def on_application_command_error(ctx, error):
    if isinstance(error, discord.CheckFailure):
        await ctx.respond("You can't use this command!")
    elif isinstance(error, discord.ApplicationCommandInvokeError):
        await ctx.respond("Something went wrong!")
        raise error  # Re-raise to log the full error

Build docs developers (and LLMs) love