Discord.JS catch 函数没有捕获错误

Discord.JS catch function not catching errors

我正在尝试制作一个命令,向用户直接发送命令列表,但如果无法直接发送,它会在频道中发送一条消息,告诉用户检查他们的隐私设置,以允许服务器成员直接发送私信他们。

但是,当我尝试使用“catch”功能时,它要么吐出错误,要么没有捕捉到命令。这是我当前的代码。

if(cmd=== `${prefix}test`){
    try {
    message.author.send("test")
    }
    catch(error){
    message.channel.send("Unable to send")
    }
    
  }

这个不行,如果我改成

if(cmd=== `${prefix}test`){
    try {
    message.author.send("test")
    }.catch(error){
    message.channel.send("Unable to send")
    }
    
  }

上面写着“SyntaxError: Missing catch or finally after try

我尝试了很多解决方案并查看了其他几个 Whosebug 问题,但我找不到解决方案。如果需要更多细节,请评论,我会尽力回答。

因为message.author.send()是一个异步函数;它总是 return 一个承诺。这意味着 send() returns 并退出 try 块,因此您的 catch 块永远不会 运行.

尝试等待 send() 先使用 await 关键字解决(或拒绝):

if (cmd === `${prefix}test`) {
  try {
    await message.author.send('test');
  } catch (error) {
    message.channel.send('Unable to send');
  }
}