how do i fix this? UnhandledPromiseRejectionWarning

1.5k Views Asked by At

I have this bot and whenever I use literally any commands I get this error:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:164) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

But I don't understand what the error means! I've tried to add a catch function, and I get another error like this:

"code".catch is not a function.

Talked to a few people and they dont know whats going on either. Most commands still work as expected, however a few don't.

This is my code:

const Discord = require('discord.js');
const client = new Discord.Client();
const DisTube = require('distube');
const { setMaxListeners } = 40
const distube = new DisTube(client, { searchSongs: false, emitNewSongOnly: true });
const { token } = require('./info.json');
const prefix = '>'

client.on("ready", () => {
    console.log(`${client.user.tag} has logged in!`);
    client.user.setActivity('>play', { type: 'WATCHING' });
});

    // Queue status template
    const status = (queue) => `Volume: \`${queue.volume}%\` | Filter: \`${queue.filter || "Off"}\` | Loop: \`${queue.repeatMode ? queue.repeatMode == 2 ? "All Queue" : "This Song" : "Off"}\` | Autoplay: \`${queue.autoplay ? "On" : "Off"}\``;

    // DisTube event listeners, more in the documentation page
    distube
        .on("playSong", (message, queue, song) => message.channel.send(
            `Playing \`${song.name}\` - \`${song.formattedDuration}\`\nRequested by: ${song.user}\n${status(queue)}`
        ))
        .on("addSong", (message, queue, song) => message.channel.send(
            `Added ${song.name} - \`${song.formattedDuration}\` to the queue by ${song.user}`
        ))
        .on("playList", (message, queue, playlist, song) => message.channel.send(
            `Play \`${playlist.name}\` playlist (${playlist.songs.length} songs).\nRequested by: ${song.user}\nNow playing \`${song.name}\` - \`${song.formattedDuration}\`\n${status(queue)}`
        ))
        .on("addList", (message, queue, playlist) => message.channel.send(
            `Added \`${playlist.name}\` playlist (${playlist.songs.length} songs) to queue\n${status(queue)}`
        ))
        // DisTubeOptions.searchSongs = true
        .on("searchResult", (message, result) => {
            let i = 0;
            message.channel.send(`**Choose an option from below**\n${result.map(song => `**${++i}**. ${song.name} - \`${song.formattedDuration}\``).join("\n")}\n*Enter anything else or wait 60 seconds to cancel*`);
        })
        distube.on("finish", message => message.channel.send("No more song in queue"))
        // DisTubeOptions.searchSongs = true
        .on("searchCancel", (message) => message.channel.send(`Searching canceled`))
        distube.on("error", (message, err) => message.channel.send(
        "An error encountered: " + err
         ));



client.on("message", async (message) => {
    if (message.author.bot) return;
    if (!message.content.startsWith(prefix)) return;
    const args = message.content.slice(prefix.length).trim().split(/ +/g);
    const command = args.shift();

    
    if (message.author.bot) return;



    if (command == "play") {
        if (!message.member.voice.channel) return message.reply('Join a voice channel to play some music!')
        if (!args[0]) return message.reply('You must state something to play!')
        distube.play(message, args.join("joined vc! :D"));
    }
    if (command == "stop") {
        const bot = message.guild.members.cache.get(client.user.id);
        if (!message.member.voice.channel) return message.reply('Join a voice channel to stop the music!');
        if (bot.voice.channel !== message.member.voice.channel) return message.channel.send('You are not in the same voice channel as me!');
        distube.stop(message);
        message.channel.send('You have stopped the music.');
    }

    if (command == "skip") {
        distube.skip(message);
        message.channel.send('Song Skipped')
    }
    if (["loop", "repeat"].includes(command)) {
        let mode = distube.setRepeatMode(message, parseInt(args[0]));
        mode = mode ? mode == 2 ? "Repeat queue" : "Repeat song" : "Off";
        message.channel.send("Set repeat mode to `" + mode + "`");
    }
    if (command == "queue") {
        let queue = distube.getQueue(message);
        message.channel.send('Current queue:\n' + queue.songs.map((song, id) =>
            `**${id+1}**. [${song.name}](${song.url}) - \`${song.formattedDuration}\``
        ).join("\n"));
    }
    if (command == "volume") {
        distube.setVolume(message, args[0]);
        message.reply("Volume set to " + args + ".")
    } 
    if (command == "shuffle") {
        distube.shuffle(message);
    }
    if (command = 'seek') {
    distube.seek(message, Number(args[0]));
    }   
    if (command == 'autoplay') {
        let mode = distube.toggleAutoplay(message);
        message.channel.send("Set autoplay mode to `" + (mode ? "On" : "Off") + "`");
    }
    if ([`3d`, `bassboost`, `echo`, `karaoke`, `nightcore`, `vaporwave`].includes(command)) {
        let filter = distube.setFilter(message, command);
        message.channel.send("Current queue filter: " + (filter || "Off"));
    }
    if (command == "ping") {  
      message.channel.send(`Latency is ${Date.now() - message.createdTimestamp}ms. API Latency is ${Math.round(client.ws.ping)}ms`);
    }
    if (command == "pause") {
      distube.pause
      message.channel.send("Current song paused. >unpause to unpase it!")
    }
    if (command == "unpause") {
      distube.unpause
      message.channel.send("song unpaused")
    }
    if (command == "autoplay") {
        let mode = distube.toggleAutoplay(message);
        message.channel.send("Set autoplay mode to `" + (mode ? "On" : "Off") + "`");
    }

});
client.login(token);
1

There are 1 best solutions below

2
On

First of all, welcome to stackoverflow!

The problem in your code is that the callback in the client.on('message', [the_callback]) is an async function and there are errors being thrown inside of it but it isn't wrapped by a try catch block (thats basically what the error message says). So you need to wrap the code like this:

client.on('message', () => {
  try {
    your code...
  } catch (err) {
    console.log(err);
  }
});

This will fix the UnhandledPromiseRejectionWarning and will probably lead to other errors in the code.