如何显示使用 Commander 制作的 Node js CLI 应用程序的自定义错误?

问题描述 投票:0回答:1

伙计们,这是我的代码

import chalk from "chalk";
import { Command } from "commander";

const program = new Command();

program
  .name("armath")
  .description(`A cli app to perform arithmetic operations`)
  .option("-a, --add <numbers...>", 'Add two numbers')
  .option("-s, --sub <numbers...>", "Subtract two numbers")
  .option("-m, --multiply <numbers...>", "Multiply two numbers")
  .option("-d, --divide <numbers...>", "Divide two numbers")
  .parse(process.argv);

if (!process.argv.slice(2).length) {
    console.log(chalk.green("Hello World!"));
} else if (program.opts().add) {
    const [num1, num2] = program.opts().add.map(Number);
    const sum = num1 + num2;
    console.log(chalk.green(`${num1} + ${num2} = ${sum}`));
} else if (program.opts().sub) {
    const [num1, num2] = program.opts().sub.map(Number);
    const diff = num1 - num2;
    console.log(chalk.green(`${num1} - ${num2} = ${diff}`));
} else if (program.opts().multiply) {
    const [num1, num2] = program.opts().multiply.map(Number);
    const product = num1 * num2;
    console.log(chalk.green(`${num1} x ${num2} = ${product}`));
} else if (program.opts().divide) {
    const [num1, num2] = program.opts().divide.map(Number);
    if(num2 == 0) {
        console.error(chalk.red(`Error: Division by zero!`));
    } else {
        console.log(chalk.green(`${num1} / ${num2} = ${num1 / num2}`));
    }
} else {
    console.error(chalk.red(`Error: Invalid command! Use --help for usage instructions!`));
}

现在每当我运行

node armath.js in my terminal
时,它都会显示 hello world,但是当我运行像
node armath.js -y
这样的随机内容时,它会显示
error: unknown option '-y' 
而不是我想显示类似
Error: Invalid command! Use --help for usage instructions!
的内容。有人可以帮助我吗?

如果有人能帮助我,那将非常有帮助! 预先感谢

javascript node.js node-modules node-commander
1个回答
0
投票

我很乐意帮助您为使用 Commander 构建的 Node.js CLI 应用程序创建更加用户友好的错误处理方法。以下是改进的代码,融合了所提供响应的最佳方面并解决了潜在问题:

import chalk from "chalk";
import { Command } from "commander";

const program = new Command();

program
  .name("armath")
  .description(`A cli app to perform arithmetic operations`)
  .option("-a, --add <numbers...>", 'Add two numbers')
  .option("-s, --sub <numbers...>", "Subtract two numbers")
  .option("-m, --multiply <numbers...>", "Multiply two numbers")
  .option("-d, --divide <numbers...>", "Divide two numbers")
  .parse(process.argv);

 // Handle unmatched options with a custom error message
 program.on('command:*', (cmd, args) => {
  console.error(chalk.red(`Error: Invalid command "${cmd}" or option 
"${args[0]}". Use --help for usage instructions.`));
  process.exit(1); // Exit with an error code to indicate failure
});

if (!program.args.length) {
  console.log(chalk.green("Hello World!"));
} else {
  // Perform operations based on parsed options
  // ... (your existing logic for calculations)
}

// Handle division by zero error with a specific message
program
  .option("-d, --divide <numbers...>", "Divide two numbers")
  .action((options) => {
    const [num1, num2] = options.divide.map(Number);
    if (num2 === 0) {
      console.error(chalk.red(`Error: Division by zero!`));
      process.exit(1); // Exit with an error code
    } else {
      console.log(chalk.green(`${num1} / ${num2} = ${num1 / num2}`));
    }
  });

program.parse(); // Parse options after defining the action handler for 
divide

此代码的主要改进:

集中错误处理:program.on('command:*') 事件监听器捕获所有不匹配的命令和选项,提供一致的错误消息以及使用 --help 的说明。 清晰的错误消息:错误消息内容丰富且具体,指导用户正确使用。 结构化错误处理:除以零的单独错误处理可确保正确的控制流和特定的错误消息。 进程退出并带有错误代码:在错误处理程序中使用 process.exit(1) 表明用户终端出现程序故障。 改进的除零处理:--divide 的操作处理程序在执行计算之前专门检查除零情况并显示相应的错误消息。 强大的解析顺序:program.parse() 调用是在定义 --divide 的操作处理程序之后进行的,以确保在发生潜在的被零除错误之前注册该处理程序。 通过这些增强功能,您的 CLI 应用程序将引导用户使用正确的命令和选项、优雅地处理意外输入以及针对不同的错误情况提供特定的错误消息,从而提供更加用户友好的体验。

© www.soinside.com 2019 - 2024. All rights reserved.