简体   繁体   中英

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. 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 "

I have tried many solutions and looked through several other stackoverflow questions yet I can't find a solution. If more details are needed, comment and I will try my best to answer.

It's because message.author.send() is an async function; it will always return a promise. It means that send() returns and exits the try block so your catch block will never run.

Try to wait for send() to resolve (or reject) first using the await keyword:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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