Skip to content

Commit 2336417

Browse files
Add process listeners for uncaught exceptions and unhandled rejections to prevent unwanted crashes
1 parent 9e2141f commit 2336417

1 file changed

Lines changed: 63 additions & 19 deletions

File tree

src/index.ts

Lines changed: 63 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,55 @@
1-
import "./libs/loadVariables.js"
2-
import {
3-
Client,
4-
GatewayIntentBits,
5-
Partials,
6-
Collection
7-
} from "discord.js";
1+
import "./libs/loadVariables.js";
2+
import { Client, GatewayIntentBits, Partials, Collection } from "discord.js";
83
import * as dotenv from "dotenv/config";
94
import { Command, loadCommands } from "./libs/loadCommands.js";
105
import path from "path";
11-
import fs from 'fs';
6+
import fs from "fs";
127
import { fileURLToPath, pathToFileURL } from "url";
138
import { logger } from "./libs/logger.js";
149

15-
const __dirname = fileURLToPath(new URL('.', import.meta.url));
10+
const __dirname = fileURLToPath(new URL(".", import.meta.url));
1611

1712
dotenv;
1813

14+
process.on("uncaughtException", (error) => {
15+
logger.error(
16+
JSON.stringify({
17+
type: "uncaughtException",
18+
message: error.message,
19+
stack: error?.stack,
20+
cause: error.cause,
21+
}),
22+
);
23+
});
24+
25+
process.on("unhandledRejection", (reason) => {
26+
const safeStringify = (value: unknown): string => {
27+
try {
28+
if (value instanceof Error) return value.message;
29+
return JSON.stringify(value, null, 2);
30+
} catch {
31+
try {
32+
return String(value);
33+
} catch {
34+
return "[Unstringifiable rejection]";
35+
}
36+
}
37+
};
38+
39+
const safeStack = (value: unknown): string => {
40+
if (value instanceof Error && value.stack) return value.stack;
41+
return "No stack trace available";
42+
};
43+
44+
logger.error(
45+
JSON.stringify({
46+
type: "unhandledRejection",
47+
reason: safeStringify(reason),
48+
stack: safeStack(reason),
49+
}),
50+
);
51+
});
52+
1953
const client = new Client({
2054
intents: [
2155
GatewayIntentBits.Guilds,
@@ -27,38 +61,48 @@ const client = new Client({
2761

2862
client.commands = new Collection();
2963

30-
const commandsPath = path.join(__dirname, 'commands');
31-
const commandFiles = fs.readdirSync(commandsPath).filter((file) => file.endsWith('.js') || file.endsWith('.ts'));
64+
const commandsPath = path.join(__dirname, "commands");
65+
const commandFiles = fs
66+
.readdirSync(commandsPath)
67+
.filter((file) => file.endsWith(".js") || file.endsWith(".ts"));
3268

3369
for (const file of commandFiles) {
3470
const filePath = path.join(commandsPath, file);
3571
const command = (await import(pathToFileURL(filePath).href)).default;
3672
if (command != undefined && Object.keys(command).length !== 0) {
3773
client.commands.set(command.data.name, command);
38-
logger.startup(`Loaded command ${file.replace(/\.[jt]s$/, '')}`);
74+
logger.startup(`Loaded command ${file.replace(/\.[jt]s$/, "")}`);
3975
} else {
40-
logger.warn(`Couldn't load command ${file.replace(/\.[jt]s$/, '')}`);
76+
logger.warn(`Couldn't load command ${file.replace(/\.[jt]s$/, "")}`);
4177
}
4278
}
4379

44-
const eventsPath = path.join(__dirname, 'events');
45-
const eventFiles = fs.readdirSync(eventsPath).filter((file) => file.endsWith('.js') || file.endsWith('.ts'));
80+
const eventsPath = path.join(__dirname, "events");
81+
const eventFiles = fs
82+
.readdirSync(eventsPath)
83+
.filter((file) => file.endsWith(".js") || file.endsWith(".ts"));
4684

4785
for (const file of eventFiles) {
4886
const filePath = path.join(eventsPath, file);
49-
const { once, name, execute } = (await import(pathToFileURL(filePath).href)).default;
87+
const { once, name, execute } = (await import(pathToFileURL(filePath).href))
88+
.default;
5089
if (once) {
5190
client.once(name, (...args) => execute(client, ...args));
5291
} else {
5392
client.on(name, (...args) => execute(client, ...args));
5493
}
55-
logger.startup(`Loaded event ${file.replace(/\.[jt]s$/, '')}`);
94+
logger.startup(`Loaded event ${file.replace(/\.[jt]s$/, "")}`);
5695
}
5796

58-
await loadCommands(client, process.env.CLIENT_ID, process.env.BOT_TOKEN, process.env.GUILD_ID);
97+
await loadCommands(
98+
client,
99+
process.env.CLIENT_ID,
100+
process.env.BOT_TOKEN,
101+
process.env.GUILD_ID,
102+
);
59103

60104
try {
61105
client.login(process.env.BOT_TOKEN);
62106
} catch (err) {
63-
console.log(err)
107+
console.log(err);
64108
}

0 commit comments

Comments
 (0)