import type { Interaction } from "discord.js"; import { errorMessage } from "./interactions"; import { logger } from "./logger"; export class PublicError extends Error { constructor(message: string) { super(message); this.name = "PublicError"; } } function getInteractionContext(interaction: Interaction) { const context: Record = { userId: interaction.user?.id, username: interaction.user?.username, guildId: interaction.guildId, channelId: interaction.channelId, interactionType: interaction.type, }; if (interaction.isCommand()) { context.commandName = interaction.commandName; } else if (interaction.isMessageComponent()) { context.customId = interaction.customId; context.componentType = interaction.componentType; } else if (interaction.isModalSubmit()) { context.customId = interaction.customId; } return context; } export async function handleError( interaction: Interaction, error: unknown, fallbackMessage?: string, ) { console.log("error", error); const context = getInteractionContext(interaction); if (error instanceof PublicError) return await errorMessage(interaction, error.message); logger.error( { error: error instanceof Error ? { message: error.message, stack: error.stack } : error, ...context, }, "An unexpected error occurred during interaction execution", ); return await errorMessage( interaction, fallbackMessage ?? "An unexpected error occurred, please try again later.", ); }