简体   繁体   English

Discord.JS catch function 没有抓到错误

[英]Discord.JS catch function not catching errors

I am trying to make a command that DMs the user a list of commands, but if its unable to DM them, it sends a message in the channel telling the user to check their privacy settings to allow server members to DM them.我正在尝试制作一个命令,让用户直接发送命令列表,但如果它无法发送它们,它会在频道中发送一条消息,告诉用户检查他们的隐私设置以允许服务器成员私信他们。

However, when I try to use the "catch" function, it either spits an error or doesn't catch the command.但是,当我尝试使用“catch”function 时,它要么吐出错误,要么没有捕获命令。 Here is my current code.这是我当前的代码。

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

This doesn't work, and if I change it to这不起作用,如果我将其更改为

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

it says " SyntaxError: Missing catch or finally after try "它说“ SyntaxError: Missing catch or finally after try

I have tried many solutions and looked through several other stackoverflow questions yet I can't find a solution.我尝试了很多解决方案并查看了其他几个 stackoverflow 问题,但我找不到解决方案。 If more details are needed, comment and I will try my best to answer.如果需要更多详细信息,请发表评论,我会尽力回答。

It's because message.author.send() is an async function;这是因为message.author.send()是一个异步 function; it will always return a promise. It means that send() returns and exits the try block so your catch block will never run.它将始终返回 promise。这意味着send()返回并退出try块,因此您的catch块将永远不会运行。

Try to wait for send() to resolve (or reject) first using the await keyword:尝试先使用await关键字等待send()解析(或拒绝):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM