Search code examples
javascriptasynchronousdiscorddiscord.jstry-catch

asyncronous try catch phrase not working discord.js


I am trying to implement a discord chatbot into my own bot, isn't good at handling some characters and stuff like the quotes of discord (type > and space to know that I mean). It often crashes becauses it thinks the message is empty. I wanted to use a try catch phrase so it won't crash. The complete function is asyncronous and I think that's why it isn't working how I want it to do. It still crashes without logging the thrown error.

client.on("message", async message => {
        if(message.channel.id === "1006483461747527772" && !message.author.bot){
            if(containsLetters(message.content)) {
                //console.log(message.content.length)
                try{
                    let reply = await chat.chat(message.content)
                    client.channels.cache.get("1006483461747527772").send(reply)
                } catch(err){
                    client.channels.cache.get("1006483461747527772").send(err)
                }  
                
            }
        } 
})

Solution

  • @Robotgozoooom's answer is correct that to send an error message to Discord you need to use error.message, but there's another problem: when Discord throws the Cannot send empty message error it is in an async function, so the try/catch doesn't actually catch the error. You need to add a .catch() function to the end of your async function instead of using a try/catch at all:

    if (containsLetters(message.content)) {
        let reply = await chat.chat(message.content);
        let channel = client.channels.cache.get("1006483461747527772");
        channel.send(reply).catch((err) => channel.send(err.message));
    }