You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py中触发自定义异常时如何发送带异常信息的embed消息

实现方案

discord.py 提供了全局和Cog局部两种命令异常处理机制,你可以通过捕获自定义的CustomError异常来自动发送Embed消息:

前置依赖

先确保你已经导入Embed类:

from discord import Embed

方式1:全局错误处理(适用所有命令抛出的异常)

给你的Bot实例注册on_command_error事件监听器即可:

@bot.event
async def on_command_error(ctx, error):
    # 匹配自定义异常类型
    if isinstance(error, CustomError):
        # 构造异常提示Embed
        error_embed = Embed(
            description=error.message,
            color=0xFF0000 # 可自定义Embed颜色值
        )
        # 发送到当前命令触发频道
        await ctx.send(embed=error_embed)
        return
    # 其余类型异常走默认处理逻辑,不需要可删除本行
    await bot.on_command_error(ctx, error)

方式2:Cog局部错误处理(仅处理当前Cog内命令抛出的异常)

如果你使用Cog组织代码,更推荐用局部错误处理避免污染全局逻辑:

class YourCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    # Cog专属错误处理钩子
    async def cog_command_error(self, ctx, error):
        if isinstance(error, CustomError):
            error_embed = Embed(
                description=error.message,
                color=0xFF0000
            )
            await ctx.send(embed=error_embed)
            return
        # 其余异常向上抛出给全局处理,不需要可删除本行
        raise error

    # 你的业务命令写在当前Cog内
    @commands.command()
    async def play(self, ctx):
        if not ctx.voice_client or ctx.voice_client.queue.is_empty():
            raise CustomError(message="Your queue seems to be empty.")
        # 其余业务逻辑

注意事项

  • 如果你已经注册过on_command_error全局事件,只需把CustomError的判断逻辑加到已有事件的最前面即可,避免覆盖原有逻辑
  • Embed可根据需求自定义标题、页脚、时间戳等属性,只要保留description=error.message即可满足你的需求
  • 处理完自定义异常后不重新抛出错误,就不会在控制台打印异常栈

内容的提问来源于stack exchange,提问作者Alado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 15:57:03