Skip to content

Commit 00b10df

Browse files
committed
fix: improve error handling in role assignment
1 parent 45ae96c commit 00b10df

File tree

2 files changed

+25
-38
lines changed

2 files changed

+25
-38
lines changed

src/commands/onboarding/index.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,21 @@ export const onboardingCommand = createCommand({
4646

4747
collector.on('collect', async (componentInteraction) => {
4848
if (componentInteraction.customId === 'onboarding_add_role') {
49-
const member = await guild.members.fetch(componentInteraction.user.id);
50-
await addRoleToUser(member, onboardingRole, componentInteraction);
49+
try {
50+
const member = await guild.members.fetch(componentInteraction.user.id);
51+
await addRoleToUser(member, onboardingRole);
52+
53+
await componentInteraction.reply({
54+
content: `You have been given the ${onboardingRole.name} role!`,
55+
flags: MessageFlags.Ephemeral,
56+
});
57+
} catch (error) {
58+
await componentInteraction.reply({
59+
content: `Failed to add role. Please contact an administrator.`,
60+
flags: MessageFlags.Ephemeral,
61+
});
62+
console.error('Error adding role:\n', error);
63+
}
5164
}
5265
});
5366
},

src/util/addRoleToUser.ts

Lines changed: 10 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,14 @@
1-
import {
2-
type ButtonInteraction,
3-
type CacheType,
4-
type ChannelSelectMenuInteraction,
5-
type GuildMember,
6-
type MentionableSelectMenuInteraction,
7-
MessageFlags,
8-
type Role,
9-
type RoleSelectMenuInteraction,
10-
type StringSelectMenuInteraction,
11-
type UserSelectMenuInteraction,
12-
} from 'discord.js';
1+
import type { GuildMember, Role } from 'discord.js';
132

14-
type ComponentInteraction =
15-
| ButtonInteraction<CacheType>
16-
| StringSelectMenuInteraction<CacheType>
17-
| UserSelectMenuInteraction<CacheType>
18-
| RoleSelectMenuInteraction<CacheType>
19-
| MentionableSelectMenuInteraction<CacheType>
20-
| ChannelSelectMenuInteraction<CacheType>;
21-
22-
export async function addRoleToUser(
23-
member: GuildMember,
24-
role: Role,
25-
interaction: ComponentInteraction
26-
) {
3+
export async function addRoleToUser(member: GuildMember, role: Role): Promise<void> {
274
const hasRole = member.roles.cache.has(role.id);
28-
if (hasRole) {
29-
await interaction.reply({
30-
content: `You already have the ${role.name} role.`,
31-
flags: MessageFlags.Ephemeral,
32-
});
33-
} else {
34-
await member.roles.add(role);
35-
await interaction.reply({
36-
content: `You have been given the ${role.name} role!`,
37-
flags: MessageFlags.Ephemeral,
38-
});
5+
if (!hasRole) {
6+
try {
7+
await member.roles.add(role);
8+
} catch (error) {
9+
throw new Error(
10+
`Failed to add role "${role.name}" to user "${member.user.username}": ${error instanceof Error ? error.message : String(error)}`
11+
);
12+
}
3913
}
4014
}

0 commit comments

Comments
 (0)