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());
}
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());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以简单地使用 Javascript 的
try
和catch
语句。这样,即使错误仍然发生,也不会破坏您的代码或机器人。它将继续运行,没有任何问题。如果您不想显示任何内容并希望继续运行机器人:
如果您希望将错误打印到控制台并继续运行机器人。然后你可以在catch语句下添加一个
console.log()
:You can simply use the
try
andcatch
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:
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: