Added new tryCatch wrapper

This commit is contained in:
2025-03-20 23:41:18 +01:00
parent e555417e13
commit 95f9bb723f
16 changed files with 255 additions and 269 deletions

View File

@@ -1,16 +1,18 @@
import { REST, Routes } from "discord.js" import { REST, Routes } from "discord.js"
import env from "../src/utils/Env" import env from "../src/utils/Env"
import tryCatch from "../src/utils/Functions/trycatch"
import { log } from "../src/utils/Logger" import { log } from "../src/utils/Logger"
const rest = new REST({ version: "10" }).setToken(env.dev.DEVTOKEN) const rest = new REST({ version: "10" }).setToken(env.dev.DEVTOKEN)
try { const [error] = await tryCatch(deleteCommands())
if (error) log(error, "error")
async function deleteCommands() {
log("Started deleting application (/) commands.", "info") log("Started deleting application (/) commands.", "info")
await rest.put( await rest.put(
Routes.applicationGuildCommands(env.dev.DEVID, env.dev.GUILDID), Routes.applicationGuildCommands(env.dev.DEVID, env.dev.GUILDID),
{ body: [] } { body: [] }
) )
log("Successfully deleted application (/) commands.", "info") log("Successfully deleted application (/) commands.", "info")
} catch (error) {
console.error(error)
} }

View File

@@ -2,6 +2,7 @@ import { REST, RESTPutAPIApplicationCommandsJSONBody, Routes } from "discord.js"
import fs from "node:fs" import fs from "node:fs"
import { ICommand } from "../src/typings" import { ICommand } from "../src/typings"
import env from "../src/utils/Env" import env from "../src/utils/Env"
import tryCatch from "../src/utils/Functions/trycatch"
import { log } from "../src/utils/Logger" import { log } from "../src/utils/Logger"
const rest = new REST({ version: "10" }).setToken(env.prod.TOKEN) const rest = new REST({ version: "10" }).setToken(env.prod.TOKEN)
@@ -18,7 +19,10 @@ for (const file of contentMenuCommands) {
commands.push(command.data.toJSON()) commands.push(command.data.toJSON())
} }
try { const [error] = await tryCatch(updateCommands())
if (error) log(error, "error")
async function updateCommands() {
log(`Started refreshing ${commands.length} application (/) commands.`, "info", { type: "preset", color: "green" }) log(`Started refreshing ${commands.length} application (/) commands.`, "info", { type: "preset", color: "green" })
const commandsString = commands.map(command => " " + command.name) const commandsString = commands.map(command => " " + command.name)
@@ -31,6 +35,4 @@ try {
log(`Successfully reloaded ${commands.length} application (/) commands.`, "info", { type: "preset", color: "green" }) log(`Successfully reloaded ${commands.length} application (/) commands.`, "info", { type: "preset", color: "green" })
process.exit(0) process.exit(0)
}) })
} catch (error) {
console.error(error)
} }

View File

@@ -2,6 +2,7 @@ import { REST, RESTPutAPIApplicationCommandsJSONBody, Routes } from "discord.js"
import fs from "fs" import fs from "fs"
import { ICommand } from "../src/typings" import { ICommand } from "../src/typings"
import env from "../src/utils/Env" import env from "../src/utils/Env"
import tryCatch from "../src/utils/Functions/trycatch"
import { log } from "../src/utils/Logger" import { log } from "../src/utils/Logger"
const rest = new REST({ version: "10" }).setToken(env.dev.DEVTOKEN) const rest = new REST({ version: "10" }).setToken(env.dev.DEVTOKEN)
@@ -22,7 +23,10 @@ for (const file of contentMenuCommands) {
} }
} }
try { const [error] = await tryCatch(updateCommands())
if (error) log(error, "error")
async function updateCommands() {
log(`Started refreshing ${commands.length} application (/) commands.`, "info") log(`Started refreshing ${commands.length} application (/) commands.`, "info")
await rest.put( await rest.put(
@@ -32,6 +36,4 @@ try {
log(`Successfully reloaded ${commands.length} application (/) commands.`, "info") log(`Successfully reloaded ${commands.length} application (/) commands.`, "info")
process.exit(0) process.exit(0)
}) })
} catch (error) {
console.error(error)
} }

View File

@@ -1,7 +1,8 @@
import { InteractionContextType, PermissionFlagsBits, SlashCommandBuilder, User, userMention } from "discord.js" import { InteractionContextType, PermissionFlagsBits, SlashCommandBuilder, userMention } from "discord.js"
import { devMessage, embedColor } from "~/config/options" import { devMessage, embedColor } from "~/config/options"
import { ICommand } from "~/typings" import { ICommand } from "~/typings"
import logToChannel from "~/utils/Functions/logtochannel" import logToChannel from "~/utils/Functions/logtochannel"
import tryCatch from "~/utils/Functions/trycatch"
export default { export default {
name: "unban", name: "unban",
@@ -34,7 +35,6 @@ export default {
const userid = interaction.options.getString("user")! const userid = interaction.options.getString("user")!
const reason = interaction.options.getString("reason") || "No reason provided" const reason = interaction.options.getString("reason") || "No reason provided"
const mod = interaction.user const mod = interaction.user
let user: User
if (userid === "none") { if (userid === "none") {
await interaction.editReply({ await interaction.editReply({
@@ -46,10 +46,9 @@ export default {
return return
} }
try { const [e, user] = await tryCatch(interaction.client.users.fetch(userid))
user = await interaction.client.users.fetch(userid)
// eslint-disable-next-line @typescript-eslint/no-unused-vars if (e) {
} catch (error) {
await interaction.editReply({ await interaction.editReply({
embeds: [{ embeds: [{
description: "The user you specified is not valid", description: "The user you specified is not valid",

View File

@@ -4,6 +4,7 @@ import { addWaitingList, getWaitingLists, removeWaitingList } from "src/drizzle/
import { embedColor, hypixelGuildID, waitingListChannel, waitingListMessage } from "~/config/options" import { embedColor, hypixelGuildID, waitingListChannel, waitingListMessage } from "~/config/options"
import { waitingListRole } from "~/config/roles" import { waitingListRole } from "~/config/roles"
import { IButton } from "~/typings" import { IButton } from "~/typings"
import tryCatch from "~/utils/Functions/trycatch"
import { getGuild, getIGN } from "~/utils/Hypixel" import { getGuild, getIGN } from "~/utils/Hypixel"
import { log } from "~/utils/Logger" import { log } from "~/utils/Logger"
@@ -82,7 +83,11 @@ export default {
}) })
if (process.env.NODE_ENV === "dev") return if (process.env.NODE_ENV === "dev") return
try {
const [error] = await tryCatch(updateWaitingList())
if (error) return log("Error while trying to update waiting list.", "error")
async function updateWaitingList() {
const channel = guild.channels.cache.get(waitingListChannel) as TextChannel const channel = guild.channels.cache.get(waitingListChannel) as TextChannel
const wlmessage = await channel!.messages.fetch(waitingListMessage) const wlmessage = await channel!.messages.fetch(waitingListMessage)
@@ -125,12 +130,6 @@ export default {
timestamp: new Date().toISOString() timestamp: new Date().toISOString()
}] }]
}) })
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (err) {
log(
"Error while trying to update waiting list.",
"error"
)
} }
} }
} as IButton } as IButton

View File

@@ -6,6 +6,7 @@ import { guild as guildQuestions } from "~/config/questions"
import { guildRole } from "~/config/roles" import { guildRole } from "~/config/roles"
import { IButton } from "~/typings" import { IButton } from "~/typings"
import applicationQuestions from "~/utils/Functions/applicationquestions" import applicationQuestions from "~/utils/Functions/applicationquestions"
import tryCatch from "~/utils/Functions/trycatch"
export default { export default {
name: "guildapply", name: "guildapply",
@@ -37,8 +38,7 @@ export default {
return return
} }
try { const [error] = await tryCatch(user.send({
await user.send({
embeds: [{ embeds: [{
title: "Guild Application", title: "Guild Application",
description: "If you wish to proceed with your application, please type `yes` otherwise type `cancel`.\n\n" + description: "If you wish to proceed with your application, please type `yes` otherwise type `cancel`.\n\n" +
@@ -46,9 +46,8 @@ export default {
"You have a minute to respond to this message.", "You have a minute to respond to this message.",
color: embedColor color: embedColor
}] }]
}) }))
// eslint-disable-next-line @typescript-eslint/no-unused-vars if (error) {
} catch (error) {
await interaction.editReply("Please enable your DMs.") await interaction.editReply("Please enable your DMs.")
return return
} }

View File

@@ -5,6 +5,7 @@ import { inactivity } from "~/config/questions"
import { beast, gm, guildRole, guildStaff, leader, member, staff } from "~/config/roles" import { beast, gm, guildRole, guildStaff, leader, member, staff } from "~/config/roles"
import { IButton } from "~/typings" import { IButton } from "~/typings"
import applicationQuestions from "~/utils/Functions/applicationquestions" import applicationQuestions from "~/utils/Functions/applicationquestions"
import tryCatch from "~/utils/Functions/trycatch"
const guildRoles = [gm, leader, staff, beast, member, guildStaff, guildRole] const guildRoles = [gm, leader, staff, beast, member, guildStaff, guildRole]
export default { export default {
@@ -32,8 +33,7 @@ export default {
return inactivity[n - 1].r return inactivity[n - 1].r
} }
try { const [error] = await tryCatch(user.send({
await user.send({
embeds: [{ embeds: [{
title: "Guild Inactivity Log", title: "Guild Inactivity Log",
description: "Please answer the following questions to submit an inactivity log for the guild.\n" + description: "Please answer the following questions to submit an inactivity log for the guild.\n" +
@@ -43,9 +43,8 @@ export default {
"You have a minute to respond to this message.", "You have a minute to respond to this message.",
color: embedColor color: embedColor
}] }]
}) }))
// eslint-disable-next-line @typescript-eslint/no-unused-vars if (error) {
} catch (error) {
await interaction.reply({ await interaction.reply({
content: "Please enable your DMs.", content: "Please enable your DMs.",
flags: MessageFlags.Ephemeral flags: MessageFlags.Ephemeral

View File

@@ -7,6 +7,7 @@ import { guildRole, guildStaff } from "~/config/roles"
import { IButton } from "~/typings" import { IButton } from "~/typings"
import env from "~/utils/Env" import env from "~/utils/Env"
import applicationQuestions from "~/utils/Functions/applicationquestions" import applicationQuestions from "~/utils/Functions/applicationquestions"
import tryCatch from "~/utils/Functions/trycatch"
export default { export default {
name: "staffapply", name: "staffapply",
@@ -54,8 +55,7 @@ export default {
return return
} }
try { const [error] = await tryCatch(user.send({
await user.send({
embeds: [{ embeds: [{
title: "Staff Application", title: "Staff Application",
description: "If you wish to proceed with your application, please type `yes` otherwise type `cancel`.\n\n" + description: "If you wish to proceed with your application, please type `yes` otherwise type `cancel`.\n\n" +
@@ -63,9 +63,8 @@ export default {
"You have a minute to respond to this message.", "You have a minute to respond to this message.",
color: embedColor color: embedColor
}] }]
}) }))
// eslint-disable-next-line @typescript-eslint/no-unused-vars if (error) {
} catch (error) {
await interaction.editReply("Please enable your DMs.") await interaction.editReply("Please enable your DMs.")
return return
} }

View File

@@ -1,7 +1,8 @@
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder, GuildMember, Message } from "discord.js" import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder, Message } from "discord.js"
import { removeGuildApp } from "src/drizzle/functions" import { removeGuildApp } from "src/drizzle/functions"
import { embedColor } from "~/config/options" import { embedColor } from "~/config/options"
import { IModal } from "~/typings" import { IModal } from "~/typings"
import tryCatch from "~/utils/Functions/trycatch"
export default { export default {
name: "denyreasonbox", name: "denyreasonbox",
@@ -38,13 +39,7 @@ export default {
] ]
}) })
let applicant: GuildMember | null const [, applicant] = await tryCatch(guild.members.fetch(applicantId))
try {
applicant = await guild.members.fetch(applicantId)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (error) {
applicant = null
}
const dmMessage = new EmbedBuilder() const dmMessage = new EmbedBuilder()
.setDescription( .setDescription(

View File

@@ -5,6 +5,7 @@ import { embedColor } from "~/config/options"
import { IAutocomplete } from "~/typings" import { IAutocomplete } from "~/typings"
import { ExtendedClient as Client } from "~/utils/Client" import { ExtendedClient as Client } from "~/utils/Client"
import logToChannel from "~/utils/Functions/logtochannel" import logToChannel from "~/utils/Functions/logtochannel"
import tryCatch from "../Functions/trycatch"
import { log } from "../Logger" import { log } from "../Logger"
type FileType = "js" | "ts" type FileType = "js" | "ts"
@@ -28,9 +29,9 @@ export default async function loadAutocompleteEvents(client: Client, ft: FileTyp
return return
} }
try { const [error] = await tryCatch(autocomplete.execute({ interaction, client }))
await autocomplete.execute({ interaction, client }) if (!error) return
} catch (error) {
if (process.env.NODE_ENV !== "dev") { if (process.env.NODE_ENV !== "dev") {
await logToChannel("error", { await logToChannel("error", {
embeds: [{ embeds: [{
@@ -45,6 +46,5 @@ export default async function loadAutocompleteEvents(client: Client, ft: FileTyp
}) })
} }
log(error, "error") log(error, "error")
}
}) })
} }

View File

@@ -5,6 +5,7 @@ import { embedColor } from "~/config/options"
import { IButton } from "~/typings" import { IButton } from "~/typings"
import { ExtendedClient as Client } from "~/utils/Client" import { ExtendedClient as Client } from "~/utils/Client"
import logToChannel from "~/utils/Functions/logtochannel" import logToChannel from "~/utils/Functions/logtochannel"
import tryCatch from "../Functions/trycatch"
import { log } from "../Logger" import { log } from "../Logger"
type FileType = "js" | "ts" type FileType = "js" | "ts"
@@ -35,9 +36,9 @@ export default async function loadButtonEvents(client: Client, ft: FileType) {
return return
} }
try { const [error] = await tryCatch(button.execute({ interaction, client }))
await button.execute({ interaction, client }) if (!error) return
} catch (error) {
if (process.env.NODE_ENV !== "dev") { if (process.env.NODE_ENV !== "dev") {
await logToChannel("error", { await logToChannel("error", {
embeds: [{ embeds: [{
@@ -69,6 +70,5 @@ export default async function loadButtonEvents(client: Client, ft: FileType) {
}] }]
}) })
} }
}
}) })
} }

View File

@@ -5,6 +5,7 @@ import { embedColor } from "~/config/options"
import { ICommand } from "~/typings" import { ICommand } from "~/typings"
import { ExtendedClient as Client } from "~/utils/Client" import { ExtendedClient as Client } from "~/utils/Client"
import logToChannel from "~/utils/Functions/logtochannel" import logToChannel from "~/utils/Functions/logtochannel"
import tryCatch from "../Functions/trycatch"
import { log } from "../Logger" import { log } from "../Logger"
type FileType = "js" | "ts" type FileType = "js" | "ts"
@@ -33,9 +34,9 @@ export default async function loadSlashCommandsEvents(client: Client, ft: FileTy
return return
} }
try { const [error] = await tryCatch(command.execute({ interaction, client }))
await command.execute({ interaction, client }) if (!error) return
} catch (error) {
if (process.env.NODE_ENV !== "dev") { if (process.env.NODE_ENV !== "dev") {
await logToChannel("error", { await logToChannel("error", {
embeds: [{ embeds: [{
@@ -67,6 +68,5 @@ export default async function loadSlashCommandsEvents(client: Client, ft: FileTy
}] }]
}) })
} }
}
}) })
} }

View File

@@ -5,6 +5,7 @@ import { embedColor } from "~/config/options"
import { IContextMenu } from "~/typings" import { IContextMenu } from "~/typings"
import { ExtendedClient as Client } from "~/utils/Client" import { ExtendedClient as Client } from "~/utils/Client"
import logToChannel from "~/utils/Functions/logtochannel" import logToChannel from "~/utils/Functions/logtochannel"
import tryCatch from "../Functions/trycatch"
import { log } from "../Logger" import { log } from "../Logger"
type FileType = "js" | "ts" type FileType = "js" | "ts"
@@ -33,9 +34,9 @@ export default async function loadContextMenuEvents(client: Client, ft: FileType
return return
} }
try { const [error] = await tryCatch(command.execute({ interaction, client }))
await command.execute({ interaction, client }) if (!error) return
} catch (error) {
if (process.env.NODE_ENV !== "dev") { if (process.env.NODE_ENV !== "dev") {
await logToChannel("error", { await logToChannel("error", {
embeds: [{ embeds: [{
@@ -67,6 +68,5 @@ export default async function loadContextMenuEvents(client: Client, ft: FileType
}] }]
}) })
} }
}
}) })
} }

View File

@@ -5,6 +5,7 @@ import { embedColor } from "~/config/options"
import { IModal } from "~/typings" import { IModal } from "~/typings"
import { ExtendedClient as Client } from "~/utils/Client" import { ExtendedClient as Client } from "~/utils/Client"
import logToChannel from "~/utils/Functions/logtochannel" import logToChannel from "~/utils/Functions/logtochannel"
import tryCatch from "../Functions/trycatch"
import { log } from "../Logger" import { log } from "../Logger"
type FileType = "js" | "ts" type FileType = "js" | "ts"
@@ -32,9 +33,9 @@ export default async function loadModalEvents(client: Client, ft: FileType) {
return return
} }
try { const [error] = await tryCatch(modal.execute({ interaction, client }))
await modal.execute({ interaction, client }) if (!error) return
} catch (error) {
if (process.env.NODE_ENV !== "dev") { if (process.env.NODE_ENV !== "dev") {
await logToChannel("error", { await logToChannel("error", {
embeds: [{ embeds: [{
@@ -65,6 +66,5 @@ export default async function loadModalEvents(client: Client, ft: FileType) {
}] }]
}) })
} }
}
}) })
} }

View File

@@ -0,0 +1,14 @@
type Success<T> = [null, T]
type Failure<E> = [E, null]
type Result<T, E = Error> = Success<T> | Failure<E>
export default async function tryCatch<T, E = Error>(promise: Promise<T>): Promise<Result<T, E>> {
try {
const data = await promise
return [null, data]
} catch (error) {
return [error as E, null]
}
}

View File

@@ -1,6 +1,7 @@
import axios from "axios" import axios, { AxiosError, AxiosResponse } from "axios"
import { IGuild, IGuildData, IPlayer, IPlayerData } from "~/typings" import { IGuild, IGuildData, IPlayer, IPlayerData } from "~/typings"
import env from "~/utils/Env" import env from "~/utils/Env"
import tryCatch from "../Functions/trycatch"
const apikey = env.prod.HYPIXELAPIKEY const apikey = env.prod.HYPIXELAPIKEY
const mojang = "https://api.mojang.com/users/profiles/minecraft/" const mojang = "https://api.mojang.com/users/profiles/minecraft/"
const mojanguuid = "https://sessionserver.mojang.com/session/minecraft/profile/" const mojanguuid = "https://sessionserver.mojang.com/session/minecraft/profile/"
@@ -22,70 +23,45 @@ type IGNData = {
} }
async function getUUID(ign: string): Promise<string | null> { async function getUUID(ign: string): Promise<string | null> {
try { const [e, d] = await tryCatch<AxiosResponse<UUIDData>, AxiosError>(axios.get<UUIDData>(mojang + ign))
const req = await axios.get<UUIDData>(mojang + ign) if (e) return null
return req.data.id return d.data.id
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (err) {
return null
}
} }
async function getIGN(uuid: string): Promise<string | null> { async function getIGN(uuid: string): Promise<string | null> {
try { const [e, d] = await tryCatch<AxiosResponse<IGNData>, AxiosError>(axios.get<IGNData>(mojanguuid + uuid))
const req = await axios.get<IGNData>(mojanguuid + uuid) if (e) return null
return req.data.name return d.data.name
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (err) {
return null
}
} }
async function getPlayer(uuid: string): Promise<IPlayerData | null> { async function getPlayer(uuid: string): Promise<IPlayerData | null> {
try { const [e, d] = await tryCatch<AxiosResponse<IPlayer>, AxiosError>(axios.get<IPlayer>(hypixel, {
const req = await axios.get<IPlayer>(hypixel, {
params: { params: {
uuid: uuid uuid: uuid
}, },
headers: { headers: {
"API-Key": apikey "API-Key": apikey
} }
}) }))
if (!req.data.player) { if (e) return null
return null if (!d.data.player) return null
} return d.data.player
return req.data.player
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (err) {
return null
}
} }
async function getGuild(query: string, reqType: GuildQueryType = "player"): Promise<IGuildData | null> { async function getGuild(query: string, reqType: GuildQueryType = "player"): Promise<IGuildData | null> {
try { const [e, d] = await tryCatch<AxiosResponse<IGuild>, AxiosError>(axios.get<IGuild>(guild, {
const req = await axios.get<IGuild>(guild, {
params: { params: {
[reqType]: query [reqType]: query
}, },
headers: { headers: {
"API-Key": apikey "API-Key": apikey
} }
}) }))
if (e) return null
if (!req.data.guild) { if (!d.data.guild) return null
return null return d.data.guild
}
return req.data.guild
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (err) {
return null
}
} }
function getHeadURL(ign: string): string { const getHeadURL = (ign: string) => minotar + ign
return minotar + ign
}
export { getGuild, getHeadURL, getIGN, getPlayer, getUUID } export { getGuild, getHeadURL, getIGN, getPlayer, getUUID }