python - 如何处理自定义 NoneType 错误?
问题描述
我已经在我的机器人中实现了我自己的功能/检查。反正控制台中没有正常AttributeError
的 as 输出,但是例如: 'NoneType' object has no attribute 'requested_by'
, 所以没有AttributeError
, 因为是我自己的函数。
有没有办法通过机器人输出这个错误并可能用try/except
语句处理它?(我确实尝试过但没有成功)
这是一个例子:
@commands.command(aliases=["disconnect"])
@commands.guild_only()
@commands.check(is_audio_requester) # check what it is about
async def leave(self, ctx):
"""Leaves the voice channel, if currently in one."""
client = ctx.guild.voice_client
state = self.get_state(ctx.guild)
if client and client.channel:
await client.disconnect()
del self.states[ctx.guild.id]
else:
raise commands.CommandError("Not in a voice channel.")
await ctx.send(
embed=discord.Embed(title=":wave::skin-tone-3: I left the voice channel.",
color=self.bot.get_embed_color(ctx.guild)))
部分我仍然得到,无论出于何种原因:
'NoneType' object has no attribute 'requested_by'
导致错误的函数:
async def is_audio_requester(ctx):
"""Checks that the command sender is the song requester."""
music = ctx.bot.get_cog("Music")
state = music.get_state(ctx.guild)
permissions = ctx.channel.permissions_for(ctx.author)
if permissions.administrator or state.is_requester(ctx.author):
return True
else:
raise commands.CommandError(
"You need to be the song requester to do that.")
(这些都没有打印出来!)
我无法处理此错误,然后我可能必须从频道中删除机器人或重新启动它。leave
如果我在没有它的情况下执行命令,commands.check
它当然可以工作。有没有什么办法解决这一问题?
我已经通过 尝试了我自己的自定义错误leave.error
,但这似乎不起作用。正如预期的那样,即使通过类似的东西if XXX is None
也不起作用。在这种情况下,我也不能使用Cog.cog.command_error
文档,至少看起来是这样。
解决方案
推荐阅读
- php - 我有 2d 数组,我想交换每个数组的最后一个索引的值
- python - Python:如何根据时间点更改绘制信号的颜色?
- python - 将数字代码列表作为描述和在 Pandas 中处理的最佳方法是什么?
- python-3.x - Keras LearningRateScheduler 在批次而不是时期回调
- c - 确定一个数组是否是另一个数组的子集的程序
- node.js - 安装 ['create-react-app@latest'] 失败,代码为 1
- python - 从 Df 创建新表,显示一列的计数和另一列的算术
- machine-learning - 交叉验证中的 Cross_val_score - 它是在训练集还是测试集上执行的?
- sql - 当传感器和温度值在一分钟内超过阈值时生成警报
- swift - Swift 如何将闭包从一个函数传递到另一个函数?