I’m having an issue trying to catch an error. The error I’m wanting to catch is a 403 discord Missing Permission error. However instead of catching the error it’s causing my bot to go offline when the error occurs.
Here is how I’m trying to catch my error.
module.exports = new Command({ name: 'ban', usage: 'ban <member>', description: 'Bans a member from the server.', permission: "BAN_MEMBERS", async run(message, args, client) { const member = message.mentions.users.first() if (!member) { return message.channel.send("A member argument must be given. Example: `ban [@member]`"); } if (member) { try { message.guild.members.ban(member) message.channel.send(`${member.tag} was banned!`); } catch { //this is the line where error isn't caught? message.channel.send(`I do not have permissions to ban ${member.username}`); } } else { message.channel.send(`You do not have permissions to ban ${member.username}`); } } })
Help appreciated.
Advertisement
Answer
TextChannel.send()
and GuildMemberManager.ban()
return a Promise
, which means that they are asynchronous.
In your async
function, you are not await
ing these calls, so no errors are caught by them, and the errors are thrown at a later time.
To fix this, you can do:
- Use
await
:try { await message.guild.members.ban(member); await message.channel.send(`${member.id} was banned!`); } catch(err) { // handle errors }
- Add
.catch()
:message.guild.members.ban(member).catch((err) => {/* handle error */}); message.channel.send(`${member.id} was banned!`).catch((err) => {/* handle error */});
It should also be noted that if you decided to send a message to the channel after catching an error, it could throw another error if the bot doesn’t have permission to send messages, so you should also catch errors there too.