为什么 .catch() 无法执行任何操作?

Why does the .catch() fail to do anything?

我在 javascript 中制作了一个 discord 机器人,我制作了一个向特定频道发送消息的命令。以前可以,现在不行了。我发现,问题出在这部分代码上:

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)

Why does the .catch() fail to do anything?

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

thencatch 创建承诺。这些承诺的实现或拒绝取决于回调的作用和它们的作用return。如果回调抛出,则拒绝创建的承诺,这就是您的代码正在做的事情。

承诺的规则之一是您必须

  1. 处理拒绝,

  2. Return 承诺处理拒绝

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

因此,如果此代码是您代码的最顶层,请删除 throw err 并改为记录或以其他方式处理错误。如果这不在代码的最顶层,请完全删除 .catchthen 中的 return 承诺,以便调用者可以处理它(或调用者的调用者,或调用者的来电者的来电者等)。

这是尽可能使用 async 函数的原因之一,当您在其中使用 awaitreturn 时,它们会自动 return 承诺链。