Developer
Handlers
Error Handler

Error Handler

An error handler in a Discord bot is essential for managing and responding to errors that occur during the bot's operation. This includes handling exceptions that may arise from command execution, API calls, or other unexpected events. An effective error handler helps in maintaining the stability and reliability of the bot by gracefully managing errors and providing useful feedback to users and developers.

Project Structure

Add errorHandler.ts inside the handlers folder.

      • commandHandler.ts
      • errorHandler.ts
  • Create errorHandler.ts

    This file will contain the logic of the error handler, ensuring that any errors encountered during the bot's execution are properly managed and logged.

    src/handlers/errorHandler.ts
    import { Client, EmbedBuilder, TextChannel } from 'discord.js'
    import config from '../configs/botConfig'
    import { COLORS, EMOJIS } from '../constants/botConst'
     
    const errorHandler = (client: Client) => {
      const errorChannelId = config.ERROR_CHANNEL
     
      const sendErrorEmbed = async (title: string, description: string) => {
        const errorChannel = client.channels.cache.get(errorChannelId) as TextChannel
        if (errorChannel) {
          const errorEmbed = new EmbedBuilder()
            .setTitle(title)
            .setDescription(description)
            .setColor(COLORS.red)
            .setTimestamp()
     
          await errorChannel.send({ embeds: [errorEmbed] })
        }
      }
     
      process.on('unhandledRejection', (reason, p) => {
        console.log('[ERROR-HANDLING] :: Unhandled Rejection/Catch')
        console.log(reason, p)
     
        sendErrorEmbed(
          `${EMOJIS.failed} New Error (Error type 1)`,
          `An error just occurred in the bot console! **\n\nERROR:\n\n** \`\`\`${reason}\n\n${p}\`\`\``,
        )
      })
     
      process.on('uncaughtException', (err, origin) => {
        console.log('[ERROR-HANDLING] :: Unhandled Exception/Catch')
        console.log(err, origin)
     
        sendErrorEmbed(
          `${EMOJIS.failed} New Error (Error type 2)`,
          `An error just occurred in the bot console! **\n\nERROR:\n\n** \`\`\`${err}\n\n${origin}\`\`\``,
        )
      })
     
      process.on('uncaughtExceptionMonitor', (err, origin) => {
        console.log('[ERROR-HANDLING] :: Unhandled Exception/Catch (MONITOR)')
        console.log(err, origin)
     
        sendErrorEmbed(
          `${EMOJIS.failed} New Error (Error type 3)`,
          `An error just occurred in the bot console! **\n\nERROR:\n\n** \`\`\`${err}\n\n${origin}\`\`\``,
        )
      })
    }
     
    export default errorHandler
    ⚠️

    Please ensure to include your error channel ID in your .env file (preferred) or config.ts file.

    Alright, we have completed more than half now let's go further!