In my Discord.JS bot, I need to be able to handle all uncaught exceptions.
I understand that I can use process.on('uncaughtException',. . .'
, but I need the ability to send a message to the channel where the error was triggered (if the error was triggered by a command, of course), and send instructions to report the error (I already have the error reporting method figured out, and I know how to do it without giving them a stack trace or other info — that is not my question).
Of course, I could always just put a try
statement in every single part of the code where this is the slightest chance of an error, but this would get very messy. Of course, I could have a module that does the error handling, but what happens if I need to add another argument to the error handler that will require a change in the try statements? I will have to spend hours going through every single file in the bot.
I understand that I will probably need to have some try statements and other error handling methods, but I need to find a more efficient way to do this if possible.
Edit: Yes, I have already tried using a try-catch statement in the command handler. It did nothing. Code:
const {bot} = require('../index');
const { logError } = require("./utils/ErrorHandling.js");
bot.on("interactionCreate", async interaction => {
if (!interaction.isCommand()) return;
let cmd = interaction.commandName;
if (bot.commands.has(cmd)) {
command = bot.commands.get(cmd);
} else {
command = bot.commands.get(bot.aliases.get(cmd));
}
try {
if (command) command.run(bot, interaction);
} catch (e) {
logError(e, interaction.channel);
}
});
Error handler module:
const { errorLoggingWebhook, supportServer } = require("../config.json")
const fetch = require("node-fetch");
module.exports = {
"logError": (error, discordChannel) => {
var errorID = createUUID();
var params = {
username: "Aspectfully Error Logging",
content: `**${errorID}**:
```
${error}
````,
}
fetch(errorLoggingWebhook, {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(params)
}).then(res => {
console.log(res);
})
return discordChannel.send(`An error occured while running that command.
If this continues to occur, please join our [support server](${supportServer}) and tell them an error is occuring.
Also, give them the error ID `${errorID}`.`)
}
}
This is an error that occurs. I know there is an easy solution to prevent it from occurring, but I just haven’t implemented it yet. This way, I can test the error handling function.
(The error is because I am intentionally trying to process a page from Wikipedia that doesn’t exist using the Wikipedia API as if it does exist, therefore trying to read values that don’t exist)
C:UsersbekfeOneDriveDocumentsAspectfullycodecommandswikipedia.js:36
wikiParseContents = wikiParse(Object.values(Object.values(JSON.parse(body))[0].text)[0], `https://en.wikipedia.org/wiki/${encodeURI(suffix)}`);
^
TypeError: Cannot convert undefined or null to object
at Function.values (<anonymous>)
at C:UsersbekfeOneDriveDocumentsAspectfullycodecommandswikipedia.js:36:42
at processTicksAndRejections (node:internal/process/task_queues:96:5)
I am not asking how to solve this specific error. I already know how to solve it. The problem is that the error handler doesn’t catch it as an error — my question is about solving this specific error.
I have also tried doing the await
function this way, but I have got the same result:
const {bot} = require('../index');
const { logError } = require("../utils/ErrorHandling.js");
bot.on("interactionCreate", async interaction => {
if (!interaction.isCommand()) return;
let cmd = interaction.commandName;
if (bot.commands.has(cmd)) {
command = bot.commands.get(cmd);
} else {
command = bot.commands.get(bot.aliases.get(cmd));
}
if (command) {
try {
await command.run(bot, interaction);
} catch (e) {
logError(e, interaction.channel);
}
}
});
Bot Designer for Discord — Wiki
Error Handling
In BDScript 2 you can handle errors returned by functions or limiters (such as $cooldown[]
or $onlyIf[]
).
Error Handling Functions
$try
Used to open the Error Handling block.
$endtry
Used to close the Error Handling block.
$catch
Used to create a sub-block between $try
and $endtry
that will contain the code that will be executed when an error occurs.
$error[]
Used in the $catch
block to return error information.
Possible Arguments
command
— returns the name of the function that returned the error.message
— returns the error message that was received.source
— returns the content of the line where the error occurred.row
— returns the number of the row in the code where the error occurred.column
— returns the number of the column in the code where the error occurred.
Examples
Function Error
$nomention
$try
$color[FFFFFF]
$title[Hi]
$description[Some broken code;]
$catch
$color[E74C3C]
$title[Error Handling]
$addField[Function:;$error[command]]
$addField[Error:;$error[message]]
$endtry
Limiter Error
As a way to use Error Handling with Limiter Errors, we’ll use $cooldown[]
. With the help of Error Handling, we can make a nice cooldown error message.
To handle only the error of our limiter, we will use a temporary variable and if statements.
If $cooldown[]
returns an error, the value of the temporary variable will be set to true
(in which case our nice error message will be sent).
Note: The
error message
argument in$cooldown[]
must be left blank.
$nomention
$var[cooldownError;false]
$try
$cooldown[3m;]
$catch
$var[cooldownError;true]
$endtry
$if[$var[cooldownError]==false]
Hey $username, are you making an example for the guide?
$else
$color[E74C3C]
$author[Oops, $username!]
$authorIcon[$authorAvatar]
$title[You have a cooldown!]
$description[Come back <t:$sum[$getTimestamp;$getCooldown[normal]]:R>.]
$endif