'Discord.js, how to handle error sending private message to user with disabled privacy setting and return right after error?

Is there possible way to handle error that will return right back after error is triggered?

  if(command === 'test') {
    message.author.send('Dm Test').catch(error => {
      message.reply('I failed to send you a private message!')
      return;
    })
    //some code below, should not trigger after sending message error. 

The problem is that .catch will respond as last, how to handle this error and immediately return instead of running also code below? I tried to use try { but that didn't work.

message.author.send('👌') 
   .catch(() => message.reply("Can't send DM to your user!"));

Would like to know if there is another way to handle error. Any help will be much appreciated.



Solution 1:[1]

If you place a return before sending the error message, JavaScript will read that as you're returning the message so if you do the following:

message.author.send('?') 
   .catch(() => return message.reply("Can't send DM to your user!"));

you'll have the error message be the final command run and nothing else will follow.

Solution 2:[2]

You can use try inside of if & else statement to know if you can dm the person or not.

if(command === 'test') {
   try {
     message.author.send("Something right here")
   } catch {
     message.channel.send("I can't dm this person.")
   } else {
    //something exploration code here
   }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FinallyComplete
Solution 2 æ–°Acesyyy