JavaScript 开始执行代码前的错误检测

Error detection before code execution starts in JavaScript

是否可以在代码开始运行之前检测到错误?
我有一个 Discord 机器人,我希望命令处理程序将所有加载的命令打印到控制台以提前显示错误状态。 目前的命令处理程序:

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());
}

您可以简单地使用 Javascript 的 trycatch 语句。这样,如果错误仍然发生,它不会破坏您的代码或机器人。它将继续 运行 没有任何问题。

如果您不想显示任何内容并想继续 运行 机器人:

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
}

如果您想将错误打印到控制台并继续 运行 机器人。然后可以在catch语句下加一个console.log()

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)
}