Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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');
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading