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 env from "../src/utils/Env"
import tryCatch from "../src/utils/Functions/trycatch"
import { log } from "../src/utils/Logger"
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")
await rest.put(
Routes.applicationGuildCommands(env.dev.DEVID, env.dev.GUILDID),
{ body: [] }
)
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 { ICommand } from "../src/typings"
import env from "../src/utils/Env"
import tryCatch from "../src/utils/Functions/trycatch"
import { log } from "../src/utils/Logger"
const rest = new REST({ version: "10" }).setToken(env.prod.TOKEN)
@@ -18,7 +19,10 @@ for (const file of contentMenuCommands) {
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" })
const commandsString = commands.map(command => " " + command.name)
@@ -31,6 +35,4 @@ try {
log(`Successfully reloaded ${commands.length} application (/) commands.`, "info", { type: "preset", color: "green" })
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 { ICommand } from "../src/typings"
import env from "../src/utils/Env"
import tryCatch from "../src/utils/Functions/trycatch"
import { log } from "../src/utils/Logger"
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")
await rest.put(
@@ -32,6 +36,4 @@ try {
log(`Successfully reloaded ${commands.length} application (/) commands.`, "info")
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 { ICommand } from "~/typings"
import logToChannel from "~/utils/Functions/logtochannel"
import tryCatch from "~/utils/Functions/trycatch"
export default {
name: "unban",
@@ -34,7 +35,6 @@ export default {
const userid = interaction.options.getString("user")!
const reason = interaction.options.getString("reason") || "No reason provided"
const mod = interaction.user
let user: User
if (userid === "none") {
await interaction.editReply({
@@ -46,10 +46,9 @@ export default {
return
}
try {
user = await interaction.client.users.fetch(userid)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (error) {
const [e, user] = await tryCatch(interaction.client.users.fetch(userid))
if (e) {
await interaction.editReply({
embeds: [{
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 { waitingListRole } from "~/config/roles"
import { IButton } from "~/typings"
import tryCatch from "~/utils/Functions/trycatch"
import { getGuild, getIGN } from "~/utils/Hypixel"
import { log } from "~/utils/Logger"
@@ -82,7 +83,11 @@ export default {
})
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 wlmessage = await channel!.messages.fetch(waitingListMessage)
@@ -125,12 +130,6 @@ export default {
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

View File

@@ -6,6 +6,7 @@ import { guild as guildQuestions } from "~/config/questions"
import { guildRole } from "~/config/roles"
import { IButton } from "~/typings"
import applicationQuestions from "~/utils/Functions/applicationquestions"
import tryCatch from "~/utils/Functions/trycatch"
export default {
name: "guildapply",
@@ -37,8 +38,7 @@ export default {
return
}
try {
await user.send({
const [error] = await tryCatch(user.send({
embeds: [{
title: "Guild Application",
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.",
color: embedColor
}]
})
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (error) {
}))
if (error) {
await interaction.editReply("Please enable your DMs.")
return
}

View File

@@ -5,6 +5,7 @@ import { inactivity } from "~/config/questions"
import { beast, gm, guildRole, guildStaff, leader, member, staff } from "~/config/roles"
import { IButton } from "~/typings"
import applicationQuestions from "~/utils/Functions/applicationquestions"
import tryCatch from "~/utils/Functions/trycatch"
const guildRoles = [gm, leader, staff, beast, member, guildStaff, guildRole]
export default {
@@ -32,8 +33,7 @@ export default {
return inactivity[n - 1].r
}
try {
await user.send({
const [error] = await tryCatch(user.send({
embeds: [{
title: "Guild Inactivity Log",
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.",
color: embedColor
}]
})
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (error) {
}))
if (error) {
await interaction.reply({
content: "Please enable your DMs.",
flags: MessageFlags.Ephemeral

View File

@@ -7,6 +7,7 @@ import { guildRole, guildStaff } from "~/config/roles"
import { IButton } from "~/typings"
import env from "~/utils/Env"
import applicationQuestions from "~/utils/Functions/applicationquestions"
import tryCatch from "~/utils/Functions/trycatch"
export default {
name: "staffapply",
@@ -54,8 +55,7 @@ export default {
return
}
try {
await user.send({
const [error] = await tryCatch(user.send({
embeds: [{
title: "Staff Application",
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.",
color: embedColor
}]
})
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (error) {
}))
if (error) {
await interaction.editReply("Please enable your DMs.")
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 { embedColor } from "~/config/options"
import { IModal } from "~/typings"
import tryCatch from "~/utils/Functions/trycatch"
export default {
name: "denyreasonbox",
@@ -38,13 +39,7 @@ export default {
]
})
let applicant: GuildMember | null
try {
applicant = await guild.members.fetch(applicantId)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (error) {
applicant = null
}
const [, applicant] = await tryCatch(guild.members.fetch(applicantId))
const dmMessage = new EmbedBuilder()
.setDescription(

View File

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

View File

@@ -5,6 +5,7 @@ import { embedColor } from "~/config/options"
import { IButton } from "~/typings"
import { ExtendedClient as Client } from "~/utils/Client"
import logToChannel from "~/utils/Functions/logtochannel"
import tryCatch from "../Functions/trycatch"
import { log } from "../Logger"
type FileType = "js" | "ts"
@@ -35,9 +36,9 @@ export default async function loadButtonEvents(client: Client, ft: FileType) {
return
}
try {
await button.execute({ interaction, client })
} catch (error) {
const [error] = await tryCatch(button.execute({ interaction, client }))
if (!error) return
if (process.env.NODE_ENV !== "dev") {
await logToChannel("error", {
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 { ExtendedClient as Client } from "~/utils/Client"
import logToChannel from "~/utils/Functions/logtochannel"
import tryCatch from "../Functions/trycatch"
import { log } from "../Logger"
type FileType = "js" | "ts"
@@ -33,9 +34,9 @@ export default async function loadSlashCommandsEvents(client: Client, ft: FileTy
return
}
try {
await command.execute({ interaction, client })
} catch (error) {
const [error] = await tryCatch(command.execute({ interaction, client }))
if (!error) return
if (process.env.NODE_ENV !== "dev") {
await logToChannel("error", {
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 { ExtendedClient as Client } from "~/utils/Client"
import logToChannel from "~/utils/Functions/logtochannel"
import tryCatch from "../Functions/trycatch"
import { log } from "../Logger"
type FileType = "js" | "ts"
@@ -33,9 +34,9 @@ export default async function loadContextMenuEvents(client: Client, ft: FileType
return
}
try {
await command.execute({ interaction, client })
} catch (error) {
const [error] = await tryCatch(command.execute({ interaction, client }))
if (!error) return
if (process.env.NODE_ENV !== "dev") {
await logToChannel("error", {
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 { ExtendedClient as Client } from "~/utils/Client"
import logToChannel from "~/utils/Functions/logtochannel"
import tryCatch from "../Functions/trycatch"
import { log } from "../Logger"
type FileType = "js" | "ts"
@@ -32,9 +33,9 @@ export default async function loadModalEvents(client: Client, ft: FileType) {
return
}
try {
await modal.execute({ interaction, client })
} catch (error) {
const [error] = await tryCatch(modal.execute({ interaction, client }))
if (!error) return
if (process.env.NODE_ENV !== "dev") {
await logToChannel("error", {
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 env from "~/utils/Env"
import tryCatch from "../Functions/trycatch"
const apikey = env.prod.HYPIXELAPIKEY
const mojang = "https://api.mojang.com/users/profiles/minecraft/"
const mojanguuid = "https://sessionserver.mojang.com/session/minecraft/profile/"
@@ -22,70 +23,45 @@ type IGNData = {
}
async function getUUID(ign: string): Promise<string | null> {
try {
const req = await axios.get<UUIDData>(mojang + ign)
return req.data.id
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (err) {
return null
}
const [e, d] = await tryCatch<AxiosResponse<UUIDData>, AxiosError>(axios.get<UUIDData>(mojang + ign))
if (e) return null
return d.data.id
}
async function getIGN(uuid: string): Promise<string | null> {
try {
const req = await axios.get<IGNData>(mojanguuid + uuid)
return req.data.name
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (err) {
return null
}
const [e, d] = await tryCatch<AxiosResponse<IGNData>, AxiosError>(axios.get<IGNData>(mojanguuid + uuid))
if (e) return null
return d.data.name
}
async function getPlayer(uuid: string): Promise<IPlayerData | null> {
try {
const req = await axios.get<IPlayer>(hypixel, {
const [e, d] = await tryCatch<AxiosResponse<IPlayer>, AxiosError>(axios.get<IPlayer>(hypixel, {
params: {
uuid: uuid
},
headers: {
"API-Key": apikey
}
})
if (!req.data.player) {
return null
}
return req.data.player
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (err) {
return null
}
}))
if (e) return null
if (!d.data.player) return null
return d.data.player
}
async function getGuild(query: string, reqType: GuildQueryType = "player"): Promise<IGuildData | null> {
try {
const req = await axios.get<IGuild>(guild, {
const [e, d] = await tryCatch<AxiosResponse<IGuild>, AxiosError>(axios.get<IGuild>(guild, {
params: {
[reqType]: query
},
headers: {
"API-Key": apikey
}
})
if (!req.data.guild) {
return null
}
return req.data.guild
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (err) {
return null
}
}))
if (e) return null
if (!d.data.guild) return null
return d.data.guild
}
function getHeadURL(ign: string): string {
return minotar + ign
}
const getHeadURL = (ign: string) => minotar + ign
export { getGuild, getHeadURL, getIGN, getPlayer, getUUID }