all repos — stealth-developers @ c17ac1a822fd9ea6899e13ebefde048635ef2a33

apps/bot/src/lib/error.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
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<string, unknown> = {
		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.",
	);
}