简体   繁体   中英

Why does this try .. catch block not catch the error?

So I'm working on a ban command for my Discord bot, and with Discord role hierarchy and all that, I figured a try... catch block would do the trick if the pinged user is higher than the bot. Here's my code:

try {
    msg.mentions.members.first().ban()
} catch (error) {
    errorOccured = true
    let embed = new Discord.MessageEmbed()
    .setTitle("Error")
    .setDescription(`I do not have permissions to ban <@${msg.mentions.members.first().id}>.`)
    .setTimestamp()
    .setColor('RED')
    return msg.channel.send(embed)
}

And here's the error I'm getting:

UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions

Now, my question is, why does this catch block not catch the error? If I'm just being dumb, please explain why and how I can fix this. Thanks!

Quick edit: I already tried using the process.on('unhandledRejection'.... but for some reason that would also pick up previous errors, and I didn't know how to fix that. If you have a solution for that, even better: :)

Edit 2: Has been fixed by @TinNguyen down in the comments, thanks. ps, @Bergur's solution could probably also have been a solution. but I don't have time to test it out right now.

UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions

This Warning can be handled with:

guildMember.ban({ days: 7, reason: 'They deserved it' })
    .then(console.log)
    .catch(console.error);

A general try catch block as shown in the question will not handle that warning.

fetch() returns a Promise, meaning that there are two execution paths, with one delayed. Your general try/catch catches the "main" thread. When the "delayed" Promise execution path returns its result, that try/catch block is far long gone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM