What's the best practice to handle errors?

Is it possible to integrate a common error handler class?
3 Replies
d.js toolkit
d.js toolkit2w ago
- What's your exact discord.js npm list discord.js and node node -v version? - Not a discord.js issue? Check out #other-js-ts. - Consider reading #how-to-get-help to improve your question! - Explain what exactly your issue is. - Post the full error stack trace, not just the top part! - Show your code! - Issue solved? Press the button!
treble/luna
treble/luna2w ago
the best practise is to catch promise rejections when they occur not later on
midorina
midorinaOP2w ago
main method call:
const deleted = await interaction.channel.bulkDelete(messages, true)
.catch((err) => errorHandler(interaction, err));
const deleted = await interaction.channel.bulkDelete(messages, true)
.catch((err) => errorHandler(interaction, err));
the error handler method:
export async function errorHandler(
interaction: CommandInteraction,
error: Promise<Collection<string, Message<boolean> | PartialMessage | undefined>>
): Promise<boolean> {
console.error("[ERROR]", error);
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor("#FF0000")
.setTitle("❌ Error")
.setDescription("An error occurred while executing the command.")
],
flags: MessageFlags.Ephemeral
});

return true;
}

return false;
}
export async function errorHandler(
interaction: CommandInteraction,
error: Promise<Collection<string, Message<boolean> | PartialMessage | undefined>>
): Promise<boolean> {
console.error("[ERROR]", error);
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({
embeds: [
new EmbedBuilder()
.setColor("#FF0000")
.setTitle("❌ Error")
.setDescription("An error occurred while executing the command.")
],
flags: MessageFlags.Ephemeral
});

return true;
}

return false;
}
would this be considered the good practice? then in this case idk how I exit the method above if an error has occurred unless I use a try-catch block :Thinkfusing: I can put more details into the message yes. currently my main concern is what the best way to handle errors is. I don't want to copy and paste the method above for each method that can fail, or wrap the whole function with a try-catch block I can simply forward the message in the error promise, no?
.setDescription("An error occurred while executing the command:
.setDescription("An error occurred while executing the command:
" + error + "
")
")
hmmm....

Did you find this page helpful?