Home > database >  discord.js try catch is not working and giving me an error
discord.js try catch is not working and giving me an error

Time:09-13

Hello I am currently working on a discord bot and I keep getting an error in my unban command.

When a user is banned and I run the unban command it works fine. When the user is not banned and I run the unban command it gives me an error saying DiscordAPIError[10026]: Unknown Ban. I expect this as the user is not banned. However I have it inside of a try catch and the catch seems to never be used.

This is the command code:

const { Console } = require('console');
const fs = require('fs');
const { EmbedBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('unban')
        .setDescription('Unbans the spesified user.')
        .addUserOption(option => option
            .setName('target')
            .setDescription('The user to unban.')
            .setRequired(true)),
    async execute(interaction) {
        is_admin = false;

        var server_data_path = "./data/"   interaction.guild.id   ".json";
        
        if (fs.existsSync(server_data_path)) {
            let rawdata = fs.readFileSync(server_data_path);
            let server_data = JSON.parse(rawdata);

            let sender_id = interaction.user.id;

            if(server_data.admin.includes(sender_id)){
                is_admin = true;
            }
        }

        if(is_admin){
            let user = interaction.options.getUser('target').id;

            try{
                interaction.guild.members.unban(user);

                const success_embed = new EmbedBuilder().setColor('00ff00').setTitle("Unbanned: "   user   ".");
                interaction.reply({ embeds: [success_embed] }).then(() => setTimeout(() => interaction.deleteReply(), 5000));
            }catch (error){
                const error_embed = new EmbedBuilder().setColor('ff0000').setTitle("Could not unban the target.");
                interaction.reply({ embeds: [error_embed] }).then(() => setTimeout(() => interaction.deleteReply(), 5000));
            }
        }else{
            const error_embed = new EmbedBuilder().setColor('ff0000').setTitle("You must be an admin to use this command.");
            interaction.reply({ embeds: [error_embed] }).then(() => setTimeout(() => interaction.deleteReply(), 5000));
        }
    },
};```

CodePudding user response:

If your interaction.guild.members.unban function returns a promise, you must AWAIT for it.

CodePudding user response:

AFAI async functions don't catch errors like that.

You'll have to use .catch(error) instead or use await inside the try catch.

  • Related