Skip to content
Advertisement

Error detection before code execution starts in JavaScript

Is it possible to detect errors before the code starts to run?
I have a Discord bot, and I would like the command handler that prints all loaded commands to the console to show the status for errors in advance. Command handler at the moment:

const { readdirSync } = require("fs");
const ascii = require("ascii-table");
const list = new ascii('Commands');
list.setHeading('Command', 'Loaded');
module.exports = (bot) => {
    let commands = readdirSync(`./commands/`).filter(file => file.endsWith(".js"));
    for (let file of commands) {
        let command = require(`../commands/${file}`);
        if (command.name) {
            bot.commands.set(command.name, command);
            list.addRow(file, '✅');
        } else {
            list.addRow(file, '❌');
            continue;
        }
    }
    console.log(list.toString());
}

Advertisement

Answer

You can simply use the try and catch statements of Javascript. In this way, if an error occurs still it will not break your code or bot. It will continue running without any problem.

If you don’t want to show anything and want to continue running the bot:

try {
  const { readdirSync } = require("fs");
  const ascii = require("ascii-table");
  const list = new ascii("Commands");
  list.setHeading("Command", "Loaded");
  module.exports = (bot) => {
    let commands = readdirSync(`./commands/`).filter((file) =>
      file.endsWith(".js")
    );
    for (let file of commands) {
      let command = require(`../commands/${file}`);
      if (command.name) {
        bot.commands.set(command.name, command);
        list.addRow(file, "✅");
      } else {
        list.addRow(file, "❌");
        continue;
      }
    }
    console.log(list.toString());
  };
} catch (e) {
  // Don't do anything
}

Incase you want to print out the error to the console and continue running the bot. Then you can add a console.log() under the catch statement:

try {
  const { readdirSync } = require("fs");
  const ascii = require("ascii-table");
  const list = new ascii("Commands");
  list.setHeading("Command", "Loaded");
  module.exports = (bot) => {
    let commands = readdirSync(`./commands/`).filter((file) =>
      file.endsWith(".js")
    );
    for (let file of commands) {
      let command = require(`../commands/${file}`);
      if (command.name) {
        bot.commands.set(command.name, command);
        list.addRow(file, "✅");
      } else {
        list.addRow(file, "❌");
        continue;
      }
    }
    console.log(list.toString());
  };
} catch (e) {
  console.log(e)
}
Advertisement