首页 > 解决方案 > 为什么 .catch() 没有做任何事情?

问题描述

我正在用 javascript 制作一个不和谐的机器人,并且我制作了一个将消息发送到特定频道的命令。它以前有效,但现在无效。我发现,问题来自这部分代码:

let sugchannel = message.guild.channels.cache.find(c => c.name === "name");

  sugchannel.send(embed).then((msg) =>{
    
    message.delete();

  }).catch((err)=>{
    throw err;
  });

我解决了很多类似的问题,但没有解决问题。此外,它确实有效,如果我将其更改为

message.channel.send(embed).then...

这是错误消息:

(node:416) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
    at RequestHandler.execute (/home/runner/cutiefoxy/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async RequestHandler.push (/home/runner/cutiefoxy/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
(node:416) 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:416) [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.
(node:416) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
    at RequestHandler.execute (/home/runner/cutiefoxy/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async RequestHandler.push (/home/runner/cutiefoxy/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
(node:416) 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: 2)

标签: javascriptnode.jspromisediscord.js

解决方案


为什么 .catch() 没有做任何事情?

它确实做了一些事情,只是没有做任何有用的事情。从来没有任何意义.catch(err => { throw err; })。它所做的只是连接一个拒绝处理程序,该处理程序创建一个新的 Promise 并以它收到的相同错误拒绝它。(有一个抛出的拒绝处理程序可能是有意义的,但如果所做的只是抛出原始错误而不做任何其他事情,则不是。)

thencatch创造承诺。根据回调的作用和返回的内容,这些承诺会被履行还是被拒绝。如果回调抛出,则拒绝创建的承诺,这就是您的代码正在执行的操作。

承诺的规则之一是你必须要么

  1. 处理拒绝,

    或者

  2. 将承诺返回给可以处理拒绝的东西

通常你想要#2,然后只在代码的最顶层处理拒绝(#1)。

因此,如果此代码是代码的最高级别,请删除throw err并改为记录或以其他方式处理错误。如果这不在代码的最顶层,请.catch完全删除并返回承诺,then以便调用者可以处理它(或调用者的调用者,或调用者的调用者的调用者等)。

这是尽可能使用函数的原因之一async,当您使用它们时,它们会自动返回承诺awaitreturn


推荐阅读