I'm trying to make an error handling system in discord.js v12. In short, when the error occurs in the bot, it will DM the bot owner and send the error code. How would I do that?
If code for the bot is needed, please tell me (yeah, I'm still learning JavaScript).
EDIT: Here's my code:
function catchErr (err, message) {
client.users.cache.get("762267309661356042").send ("There was an error at channel " + message.channel + " in guild " + message.guild + ".")
client.users.cache.get("762267309661356042").send ("ERROR``` " + err + "```")
}
Then whenever an error happens in the code, I would catch it with try and catch (I used my own command handler):
try {
command(client, 'test', (message) => {
CatchThis
})
} catch (err) {
catchErr(err, message)
}
But the error still occurs and stops the bot:
ReferenceError: CatchThis is not defined
at PATH\index.js:42:3
at PATH\basic-command-handler.js:21:11
at Array.forEach (<anonymous>)
at Client.<anonymous> (PATH\util\basic-command-handler.js:17:15)
at Client.emit (node:events:406:35)
at MessageCreateAction.handle (PATH\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (PATH\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (PATH\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (PATH\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocket.onMessage (PATH\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (node:events:394:28)
at Receiver.receiverOnMessage (PATH\node_modules\ws\lib\websocket.js:983:20)
at Receiver.emit (node:events:394:28)
at Receiver.dataMessage (PATH\node_modules\ws\lib\receiver.js:517:14)
at Receiver.getData (PATH\node_modules\ws\lib\receiver.js:435:17)
Well about the error u see, you just have a CatchThis variable that it is not define. About error handling, seem like it should work for you, the error will occur only when the "try" code block will fail to execute or you can throw an Error with throw.
Going off of the code you provided; you have not defined CatchThis. So I recommend removing that undefined variable or edit your question and provide the code that has that variable.
After removing the variable, your code should look like this:
try {
command(client, 'test', (message) => {
// code to run
});
} catch (err) {
catchErr(err, message);
}
But currently; the catchErr will not be able to access message. So after removing the undefined variable, rework the code so it looks like this:
command(client, 'test', (message) => {
try {
// code to run
} catch (err) {
catchErr(err, message);
}
});