Skip to content

Error Handling

Simon Roy edited this page Feb 15, 2026 · 1 revision

Handling Errors

Errors happen! A user might provide invalid input, your API might fail, or someone might misuse a command. Let's make your bot handle these gracefully.

Types of Errors

Matrix.py has several built-in error types:

Error When It Happens
MissingArgumentError Required parameter not provided
CheckError A check function returned False
CooldownError User hit rate limit
CommandNotFoundError Command doesn't exist

Bot-Level Error Handling

Handle errors across all commands:

from matrix.errors import MissingArgumentError, CheckError, CooldownError


@bot.error(MissingArgumentError)
async def missing_arg_handler(error):
    """Handles missing arguments for any command"""
    param_name = error.param.name
    print(f"❌ Missing required parameter: {param_name}")


@bot.error(CheckError)
async def check_failed_handler(error):
    """Handles failed checks"""
    command_name = error.command.name
    print(f"❌ Check failed for command: {command_name}")


@bot.error(CooldownError)
async def cooldown_handler(error):
    """Handles cooldown errors"""
    retry_after = int(error.retry)
    print(f"⏳ On cooldown! Retry in {retry_after} seconds")

Command-Level Error Handling

Handle errors for a specific command:

@bot.command(description="Divides two numbers")
async def divide(ctx, a: int, b: int):
    result = a / b
    await ctx.reply(f"{a} ÷ {b} = {result}")

@divide.error()
async def handle_divide_errors(ctx, error):
    """Handle any errors from the divide command"""
    if isinstance(error, ZeroDivisionError):
        await ctx.reply("❌ Cannot divide by zero!")
    elif isinstance(error, ValueError):
        await ctx.reply("❌ Please provide valid numbers!")
    else:
        await ctx.reply(f"❌ An error occurred: {error}")

Handling Specific Exceptions

You can handle specific exception types:

@bot.command()
async def risky(ctx):
    raise ValueError("Something went wrong!")


@risky.error(ValueError)
async def handle_value_error(ctx, error):
    """Only handles ValueError"""
    await ctx.reply(f"Value error: {error}")


@risky.error(TypeError)
async def handle_type_error(ctx, error):
    """Only handles TypeError"""
    await ctx.reply(f"Type error: {error}")

Clone this wiki locally