【问题标题】:Why does this try .. catch block not catch the error?为什么这个 try .. catch 块没有捕捉到错误?
【发布时间】:2021-07-25 18:35:43
【问题描述】:

所以我正在为我的 Discord 机器人制定一个禁止命令,并且使用 Discord 角色层次结构和所有这些,我认为如果被 ping 的用户高于机器人,则 try ... catch 块会起到作用。这是我的代码:

try {
    msg.mentions.members.first().ban()
} catch (error) {
    errorOccured = true
    let embed = new Discord.MessageEmbed()
    .setTitle("Error")
    .setDescription(`I do not have permissions to ban <@${msg.mentions.members.first().id}>.`)
    .setTimestamp()
    .setColor('RED')
    return msg.channel.send(embed)
}

这是我得到的错误:

UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions

现在,我的问题是,为什么这个 catch 块没有捕捉到错误?如果我只是愚蠢,请解释为什么以及如何解决这个问题。谢谢!

快速编辑:我已经尝试过使用process.on('unhandledRejection' .... 但由于某种原因,这也会发现以前的错误,我不知道如何解决这个问题。如果您对此有解决方案,那就更好了! :)

编辑 2:已由 @TinNguyen 在 cmets 中修复,谢谢!附言。 @Bergur 的解决方案可能也是一个解决方案,但我现在没有时间测试它。

【问题讨论】:

  • 因为UnhandledPromiseRejectionWarning不是try中的代码引起的。
  • @Teemu 好吧,这只是我的问题;它是。在我的其余代码中,我没有使用权限,而错误清楚地表明这是它出错的原因。
  • 我不熟悉库@Teemu,但它似乎是由尝试中的代码引起的。如果他想处理他必须做的警告:guildMember.ban({ days: 7, reason: 'They deserved it' }) .then(console.log) .catch(console.error); 但是我可能错了。
  • 不知道discord,但是ban方法是异步的吗?也许将 await 放在 msg.mentions,members.first().ban() 前面就足够了
  • @TinNguyen 感谢您提供意想不到的解决方案。无论出于何种原因,try ... catch 块都不起作用,而 .catch(error =&gt; { // code here }) 确实起作用。不知道为什么,但它修复了它!

标签: javascript node.js discord discord.js


【解决方案1】:
UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions

可以通过以下方式处理此警告:

guildMember.ban({ days: 7, reason: 'They deserved it' })
    .then(console.log)
    .catch(console.error);

问题中显示的一般 try catch 块不会处理该警告。

【讨论】:

  • .ban() 的参数中的对象不是必需的,而是可选的,.then() 也是如此。如果您想在发生错误时执行一些代码,请在.catch() 中创建一个箭头函数,然后将您的代码放入,这对我来说非常适合。
猜你喜欢
  • 2017-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-05
  • 2016-01-26
相关资源
最近更新 更多