【问题标题】:Discord.js Bot - How to handle UnhandledPromiseRejectionWarning in my caseDiscord.js Bot - 在我的情况下如何处理 UnhandledPromiseRejectionWarning
【发布时间】:2021-01-12 16:32:34
【问题描述】:

我不断收到 UnhandledPromiseRejectionWarning,即使代码正常运行(部分,有时它会中断)。 那么,如何捕捉承诺拒绝的事情呢?我昨天开始使用 node.js,这真是令人困惑。

bot.on('message', async message => {
    let inGame = message.guild.roles.cache.find(role => role.name == "In-Game");
    let memberArray = message.guild.members.cache.filter(member => member.roles.cache.find(role => role == inGame)).array();

    if (message.content.startsWith(".mute2") && message.channel.name == 'admin-only') {
        memberArray.forEach(member => member.edit({mute: true}));
    }
});

【问题讨论】:

  • 我们会知道 UnhandledPromiseRejectionWarning 是什么

标签: node.js discord discord.js


【解决方案1】:

UnhandledPromiseRejectionWarning 是您在基于 Promise 的代码中遇到的其他错误的包装器,这些错误您尚未使用 try/catch 或其他东西处理。这是一个示例(不是您的代码中的错误)

(node:16189) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Access
    at RequestHandler.execute (/home/*/NODESTUFF/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:16189) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:16189) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

请注意,在 UnhandledPromiseRejectionWarning 之后,还有另一个错误:DiscordAPIError: Missing Access。

然后还有另一行在控制台中显示时您看不到,但在 SO 代码格式中非常易读:

UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。

如果您遇到类似的 API 错误,则您的机器人缺少某些权限(我怀疑)。不幸的是,代码并没有告诉您您缺少 什么 权限。我建议您为您尝试做的每件事添加烫发。

您的代码对我来说运行良好,因为我已经为我的机器人授予了静音用户、查看角色等的权限。实际上我很惊讶您不需要等待 member.edit()。如果有人知道原因,请发表评论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-10
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    相关资源
    最近更新 更多