0
votes

I am coding a discord Bot that checks if a User is on my Discord Server and if he has a certain Role. However I get an error message if the User is not on my Discord despite using catch. I have the following code:

app.post('/', (req, res) => {
const userId = req.rawBody;

try {
    bot.guilds.fetch(guildId).then(guild => {
        guild.members.fetch(userId).then(user => {
            if (user.id == userId) {
                if (user.roles.cache.has('830811473604902912'))
                {
                    console.log('User has RoleX.');
                }
            } else{
                // Member invalid
                console.log('User is not on Discord.');
                res.send('False');
            }
        });
    });
} 
catch
{
    // Member not found or other error encountered
    console.log('User is not on Discord.');
    res.send('False');
}
});

Now the Error Message is:

(node:15184) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Member at RequestHandler.execute (c:\Users\User\Desktop\DiscordBot\MyBot\node_modules\discord.js\src\rest\RequestHandler.js:154:13) at processTicksAndRejections (internal/process/task_queues.js:93:5) at async RequestHandler.push (c:\Users\User\Desktop\DiscordBot\MyBot\node_modules\discord.js\src\rest\RequestHandler.js:39:14) (Use node --trace-warnings ... to show where the warning was created)

(node:15184) 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:15184) [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.

It says I have an async function without a catch block but there clearly is a catch?

1
A standard try/catch only catches promise rejections when you use async/awaitcharlietfl

1 Answers

1
votes

You have a catch block but not on the actual promise(s). Change to:

bot.guilds.fetch(guildId).then(guild => {
    return guild.members.fetch(userId).then(user => {
        if (user.id == userId) {
            if (user.roles.cache.has('830811473604902912'))
            {
                console.log('User has RoleX.');
            }
        } else{
            // Member invalid
            console.log('User is not on Discord.');
            res.send('False');
        }
    });
})
.catch((e) => {

  // Handle error here
});