如何捕获错误并将其发送给 discord.js v12 中的机器人所有者?
2021-11-20
406
我正在尝试在 discord.js v12 中创建一个错误处理系统。简而言之,当机器人中发生错误时,它会向机器人所有者发送 DM 并发送错误代码。我该怎么做?
如果需要机器人的代码,请告诉我(是的,我还在学习 JavaScript)。
编辑:这是我的代码:
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 + "```")
}
然后,每当代码中发生错误时,我都会用 try 和 catch 捕获它(我使用了我自己的命令处理程序):
try {
command(client, 'test', (message) => {
CatchThis
})
} catch (err) {
catchErr(err, message)
}
但错误仍然发生并停止机器人:
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)
2个回答
根据您提供的代码,您尚未定义
CatchThis
。因此,我建议删除该未定义变量,或编辑您的问题并提供包含该变量的代码。
删除变量后,您的代码应如下所示:
try {
command(client, 'test', (message) => {
// code to run
});
} catch (err) {
catchErr(err, message);
}
但目前,
catchErr
将无法访问
message
。因此,删除未定义变量后,请重新编写代码,使其如下所示:
command(client, 'test', (message) => {
try {
// code to run
} catch (err) {
catchErr(err, message);
}
});
spinfal
2021-11-29
好吧,关于您看到的错误,您只是有一个未定义的 CatchThis 变量。 关于错误处理,似乎它应该适合您,只有当“try”代码块执行失败或您可以使用 throw 抛出错误时才会发生错误。
Adiv Versano
2021-11-20