Error bot discord

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...

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

Function Error

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

Limiter Error
Limiter Error

async def on_command_error(self, ctx, error): # if command has local error handler, return if hasattr(ctx.command, ‘on_error’): return # get the original exception error = getattr(error, ‘original’, error) if isinstance(error, commands.CommandNotFound): return if isinstance(error, commands.BotMissingPermissions): missing = [perm.replace(‘_’, ‘ ‘).replace(‘guild’, ‘server’).title() for perm in error.missing_perms] if len(missing) > 2: fmt = ‘{}, and {}’.format(«**, **».join(missing[:1]), missing[1]) else: fmt = ‘ and ‘.join(missing) _message = ‘I need the **{}** permission(s) to run this command.’.format(fmt) await ctx.send(_message) return if isinstance(error, commands.DisabledCommand): await ctx.send(‘This command has been disabled.’) return if isinstance(error, commands.CommandOnCooldown): await ctx.send(«This command is on cooldown, please retry in {}s.».format(math.ceil(error.retry_after))) return if isinstance(error, commands.MissingPermissions): missing = [perm.replace(‘_’, ‘ ‘).replace(‘guild’, ‘server’).title() for perm in error.missing_perms] if len(missing) > 2: fmt = ‘{}, and {}’.format(«**, **».join(missing[:1]), missing[1]) else: fmt = ‘ and ‘.join(missing) _message = ‘You need the **{}** permission(s) to use this command.’.format(fmt) await ctx.send(_message) return if isinstance(error, commands.UserInputError): await ctx.send(«Invalid input.») await self.send_command_help(ctx) return if isinstance(error, commands.NoPrivateMessage): try: await ctx.author.send(‘This command cannot be used in direct messages.’) except discord.Forbidden: pass return if isinstance(error, commands.CheckFailure): await ctx.send(«You do not have permission to use this command.») return # ignore all other exception types, but print them to stderr print(‘Ignoring exception in command {}:’.format(ctx.command), file=sys.stderr) traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)

Понравилась статья? Поделить с друзьями:
  • Error boot sequence will be taken if no selection is made lenovo что делать
  • Error boot sequence bios
  • Error boot certification verify secure booting error cause boot certification verify
  • Error boot certificate verification 1
  • Error bookmark not found