Skip to main content

Error Handling

note

This content has been taken directly from the documentation, and inherited from discord.py. It will most likely be rewritten in the future.

When our commands fail to parse we will, by default, receive a noisy error in stderr of our console that tells us that an error has happened and has been silently ignored.

In order to handle our errors, we must use something called an error handler. There is a global error handler, called on_command_error() which works like any other event in the Event Reference. This global error handler is called for every error reached.

Most of the time however, we want to handle an error local to the command itself. Luckily, commands come with local error handlers that allow us to do just that. First we decorate an error handler function with Command.error():

@bot.command()
async def info(ctx, *, member: disnake.Member):
"""Tells you some info about the member."""
msg = f"{member} joined on {member.joined_at} and has {len(member.roles)} roles."
await ctx.send(msg)


@info.error
async def info_error(ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send("I could not find that member...")

The first parameter of the error handler is the Context while the second one is an exception that is derived from CommandError. A list of errors is found in the Exceptions page of the documentation.