Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

137
Views
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.

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

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');
  }
}
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs