샘플
commander 13.1.0: Distinguish Commander error paths where exitOverride intercepts InvalidArgumentError as a CommanderError instance with commander.invalidArgument code rather than preserving the InvalidArgumentError class or wrapping standard Error exceptions
검증된 샘플 — npm commander 13.1.0: Distinguish Commander error paths where exitOverride intercepts InvalidArgumentError as a CommanderError instance with…
sha256:94607693bb374f0a65026f93ee8ff32d6560d2668a0b2e16a5e6ebc40f4ddd52
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 3
- 빌드한 서명 키
- 3
선언된 환경
node linux x64 node node npm
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-16 |
| node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-18 |
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-09-08 |
케이스
HOW- 목표
- Distinguish Commander error paths where exitOverride intercepts InvalidArgumentError as a CommanderError instance with commander.invalidArgument code rather than preserving the InvalidArgumentError class or wrapping standard Error exceptions
- 패키지
- 심벌
-
- InvalidArgumentError
- CommanderError
- Command.prototype.exitOverride
- Command.prototype.option
- Command.prototype.requiredOption
- Option.prototype.choices
- 환경
- node
- 생성일
- 2026-08-16T16:19:04Z
컨트랙트
- Throwing InvalidArgumentError inside a custom option parser causes exitOverride to throw a CommanderError instance where err instanceof InvalidArgumentError evaluates to false, err.code is 'commander.invalidArgument', and err.nestedError is undefined.
- Throwing a generic TypeError or Error from a custom option parser bypasses Commander error handling, rethrowing the raw error without code or exitCode properties.
- Invalid option choices trigger a CommanderError with code 'commander.invalidArgument' rather than an invalid choice error code or InvalidArgumentError instance.
- Omitting a requiredOption raises a CommanderError with code 'commander.missingMandatoryOptionValue' rather than 'commander.missingOption'.
- Invoking --help with exitOverride throws a CommanderError with exitCode 0 and code 'commander.helpDisplayed' rather than exiting cleanly or throwing an error code.
파일
- NOTES.md
- csx.json
- package-lock.json
- package.json
- src/index.mjs
- test/contract.mjs
소스
# Commander Input Error Paths
## Search Results
Calling `search_known_solution` returned sample `sha256:5c6d27a5983a0c5c7ab82d8867250554602d63b07860b3cdacd2dcd58f498252` (string option shorthand in `Option.implies()`), sample `sha256:05e524cd641f3e66c380604099a1c591c4fbe976012949d4819b1f3ec255ed9f` (subcommand action argument unpacking and coerce radix traps), and sample `sha256:ae82f374c5cce645bfa0fbd914f1f675540b81131e60b0b93130f5caa6b74638` (parsing user arguments with `{ from: 'user' }`). None of these address the error routing behavior of `exitOverride()` and `InvalidArgumentError`.
## Error Handling Behavior
- When custom option parsers throw `InvalidArgumentError`, Commander intercepts the error, formats the CLI context message, and throws a brand-new `CommanderError` instance with `err.code = 'commander.invalidArgument'`, discarding the original `InvalidArgumentError` instance and leaving `err.nestedError` undefined (`err instanceof InvalidArgumentError` evaluates to `false`).
- Standard JavaScript exceptions (`Error`, `TypeError`) thrown from custom option parsers bypass Commander's error handling entirely and propagate raw, skipping `exitOverride()` formatting, error codes, and help output.
- Missing mandatory options (`requiredOption`) produce error code `'commander.missingMandatoryOptionValue'` rather than `'commander.missingOption'`.
- Running with `--help` or `--version` under `exitOverride()` throws a `CommanderError` with `exitCode = 0`, meaning callers cannot assume a thrown `CommanderError` always denotes a failure.
## Failure Mode
Catching errors with `if (err instanceof InvalidArgumentError)` fails silently with a green build because the check evaluates to `false` and bypasses error recovery logic, whereas throwing standard `Error` instances in custom parsers fails loudly with an uncaught runtime exception.
{"case":{"believed":"Throwing InvalidArgumentError from a custom option parser causes exitOverride to rethrow the InvalidArgumentError instance, while throwing standard JavaScript Error instances is caught and formatted as a CommanderError.","caseId":"case:sha256:b9f7355cbcca5c119a0038a810fa07303c70ed10c526a719b68b6d4884895d59","contract":["Throwing InvalidArgumentError inside a custom option parser causes exitOverride to throw a CommanderError instance where err instanceof InvalidArgumentError evaluates to false, err.code is 'commander.invalidArgument', and err.nestedError is undefined.","Throwing a generic TypeError or Error from a custom option parser bypasses Commander error handling, rethrowing the raw error without code or exitCode properties.","Invalid option choices trigger a CommanderError with code 'commander.invalidArgument' rather than an invalid choice error code or InvalidArgumentError instance.","Omitting a requiredOption raises a CommanderError with code 'commander.missingMandatoryOptionValue' rather than 'commander.missingOption'.","Invoking --help with exitOverride throws a CommanderError with exitCode 0 and code 'commander.helpDisplayed' rather than exiting cleanly or throwing an error code."],"goal":"Distinguish Commander error paths where exitOverride intercepts InvalidArgumentError as a CommanderError instance with commander.invalidArgument code rather than preserving the InvalidArgumentError class or wrapping standard Error exceptions","kind":"HOW","packages":["pkg:npm/commander@13.1.0"],"schemaVersion":1,"symbols":["InvalidArgumentError","CommanderError","Command.prototype.exitOverride","Command.prototype.option","Command.prototype.requiredOption","Option.prototype.choices"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/commander@13.1.0"],"schemaVersion":1,"symbols":["InvalidArgumentError","CommanderError","Command.prototype.exitOverride","Command.prototype.option","Command.prototype.requiredOption","Option.prototype.choices"],"verifierAdapter":"node-typescript@1"}
{
"name": "csx-sample-commander-error-paths",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "csx-sample-commander-error-paths",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"commander": "13.1.0"
}
},
"node_modules/commander": {
"version": "13.1.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz",
"integrity": "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==",
"license": "MIT",
"engines": {
"node": ">=18"
}
}
}
}
{
"name": "csx-sample-commander-error-paths",
"version": "1.0.0",
"private": true,
"type": "module",
"license": "MIT-0",
"dependencies": {
"commander": "13.1.0"
}
}
import { Command, InvalidArgumentError, Option } from 'commander';
/**
* Custom option parser function that validates a port number using InvalidArgumentError.
*
* @param {string} value - Raw string argument from CLI
* @returns {number} Parsed port integer
* @throws {InvalidArgumentError} When the value is not an integer between 1 and 65535
*/
export function parsePort(value) {
const port = parseInt(value, 10);
if (Number.isNaN(port) || port < 1 || port > 65535) {
throw new InvalidArgumentError('Port must be an integer between 1 and 65535.');
}
return port;
}
/**
* Custom option parser function that throws a generic TypeError instead of InvalidArgumentError.
*
* @param {string} _value
* @returns {never}
* @throws {TypeError} Standard JavaScript TypeError
*/
export function parseFaulty(value) {
throw new TypeError(`Uncaught validation failure for value: ${value}`);
}
/**
* Creates and configures a CLI parser with exitOverride and suppressed output for programmatic inspection.
*
* @param {object} [options]
* @param {boolean} [options.includePort] - Whether to include the custom port option
* @param {boolean} [options.includeFaulty] - Whether to include the faulty generic error option
* @param {boolean} [options.includeChoices] - Whether to include the choices option
* @param {boolean} [options.includeRequired] - Whether to include the mandatory requiredOption
* @returns {Command} Configured Commander Command instance
*/
export function createCli(options = {}) {
const program = new Command();
program
.name('server-cli')
.exitOverride()
.configureOutput({
writeOut: () => {},
writeErr: () => {},
});
if (options.includePort) {
program.option('-p, --port <number>', 'server port', parsePort);
}
if (options.includeFaulty) {
program.option('-t, --timeout <ms>', 'timeout duration', parseFaulty);
}
if (options.includeChoices) {
program.addOption(
new Option('-e, --env <environment>', 'target environment').choices([
'dev',
'staging',
'prod',
]),
);
}
if (options.includeRequired) {
program.requiredOption('-c, --config <file>', 'configuration file path');
}
return program;
}
import { strict as assert } from 'node:assert';
import { InvalidArgumentError, CommanderError } from 'commander';
import { createCli } from '../src/index.mjs';
// 1. Throwing InvalidArgumentError inside a custom option parser causes exitOverride to throw a CommanderError instance where err instanceof InvalidArgumentError evaluates to false, err.code is 'commander.invalidArgument', and err.nestedError is undefined.
{
const cli = createCli({ includePort: true });
let caughtError;
try {
cli.parse(['node', 'server-cli', '--port', '99999']);
} catch (err) {
caughtError = err;
}
assert.ok(caughtError !== undefined, 'CLI parse must throw under exitOverride');
assert.strictEqual(
caughtError instanceof InvalidArgumentError,
false,
'exitOverride must not rethrow the original InvalidArgumentError instance',
);
assert.strictEqual(
caughtError instanceof CommanderError,
true,
'exitOverride must throw a CommanderError instance',
);
assert.strictEqual(caughtError.constructor.name, 'CommanderError');
assert.strictEqual(caughtError.code, 'commander.invalidArgument');
assert.strictEqual(caughtError.exitCode, 1);
assert.strictEqual(caughtError.nestedError, undefined);
assert.strictEqual(
caughtError.message,
"error: option '-p, --port <number>' argument '99999' is invalid. Port must be an integer between 1 and 65535.",
);
}
// 2. Throwing a generic TypeError or Error from a custom option parser bypasses Commander error handling, rethrowing the raw error without code or exitCode properties.
{
const cli = createCli({ includeFaulty: true });
let caughtError;
try {
cli.parse(['node', 'server-cli', '--timeout', 'invalid-val']);
} catch (err) {
caughtError = err;
}
assert.ok(caughtError !== undefined, 'CLI parse must throw raw exception');
assert.strictEqual(
caughtError instanceof TypeError,
true,
'Uncaught generic error must propagate as original TypeError',
);
assert.strictEqual(
caughtError instanceof CommanderError,
false,
'Generic error must not be wrapped into CommanderError',
);
assert.strictEqual(caughtError.code, undefined);
assert.strictEqual(caughtError.exitCode, undefined);
}
// 3. Invalid option choices trigger a CommanderError with code 'commander.invalidArgument' rather than an invalid choice error code or InvalidArgumentError instance.
{
const cli = createCli({ includeChoices: true });
let caughtError;
try {
cli.parse(['node', 'server-cli', '--env', 'qa']);
} catch (err) {
caughtError = err;
}
assert.ok(caughtError !== undefined, 'CLI parse must throw on invalid choice');
assert.strictEqual(caughtError instanceof InvalidArgumentError, false);
assert.strictEqual(caughtError instanceof CommanderError, true);
assert.strictEqual(caughtError.code, 'commander.invalidArgument');
assert.strictEqual(caughtError.exitCode, 1);
assert.strictEqual(
caughtError.message,
"error: option '-e, --env <environment>' argument 'qa' is invalid. Allowed choices are dev, staging, prod.",
);
}
// 4. Omitting a requiredOption raises a CommanderError with code 'commander.missingMandatoryOptionValue' rather than 'commander.missingOption'.
{
const cli = createCli({ includeRequired: true });
let caughtError;
try {
cli.parse(['node', 'server-cli']);
} catch (err) {
caughtError = err;
}
assert.ok(caughtError !== undefined, 'CLI parse must throw when required option is missing');
assert.strictEqual(caughtError instanceof CommanderError, true);
assert.strictEqual(caughtError.code, 'commander.missingMandatoryOptionValue');
assert.strictEqual(caughtError.exitCode, 1);
assert.strictEqual(
caughtError.message,
"error: required option '-c, --config <file>' not specified",
);
}
// 5. Invoking --help with exitOverride throws a CommanderError with exitCode 0 and code 'commander.helpDisplayed' rather than exiting cleanly or throwing an error code.
{
const cli = createCli();
let caughtError;
try {
cli.parse(['node', 'server-cli', '--help']);
} catch (err) {
caughtError = err;
}
assert.ok(caughtError !== undefined, '--help with exitOverride must throw');
assert.strictEqual(caughtError instanceof CommanderError, true);
assert.strictEqual(caughtError.exitCode, 0);
assert.strictEqual(caughtError.code, 'commander.helpDisplayed');
}