{"id":"e636a2d830641387","repo":"tj/commander.js","slug":"allowed-choices-are-this-argchoices-join-e636a2","errorCode":null,"errorMessage":"Allowed choices are ${this.argChoices.join(', ')}.","messagePattern":"Allowed choices are (.+?)\\.","errorType":"validation","errorClass":"InvalidArgumentError","httpStatus":null,"severity":"error","filePath":"lib/option.js","lineNumber":185,"sourceCode":"      return [value];\n    }\n\n    previous.push(value);\n    return previous;\n  }\n\n  /**\n   * Only allow option value to be one of choices.\n   *\n   * @param {string[]} values\n   * @return {Option}\n   */\n\n  choices(values) {\n    this.argChoices = values.slice();\n    this.parseArg = (arg, previous) => {\n      if (!this.argChoices.includes(arg)) {\n        throw new InvalidArgumentError(\n          `Allowed choices are ${this.argChoices.join(', ')}.`,\n        );\n      }\n      if (this.variadic) {\n        return this._collectValue(arg, previous);\n      }\n      return arg;\n    };\n    return this;\n  }\n\n  /**\n   * Return option name.\n   *\n   * @return {string}\n   */\n\n  name() {","sourceCodeStart":167,"sourceCodeEnd":203,"githubUrl":"https://github.com/tj/commander.js/blob/ba6d13ddb4243e5913367734f8c159089ffe7834/lib/option.js#L167-L203","documentation":"Thrown at parse time (not construction time) when an Option configured with .choices(values) receives a command-line argument that is not in the allowed list. The choices() method replaces the option's parseArg with a validator that throws InvalidArgumentError, which extends CommanderError with exitCode 1 and code 'commander.invalidArgument'. Commander normally catches this itself, prints the message (listing the allowed values), and exits with code 1; the message interpolates this.argChoices.join(', ').","triggerScenarios":"Defining new Option('--color <c>').choices(['red','green']) (or .option('--color <c>').choices(...)) and the end user running `cli --color blue`. Also triggered by variadic choice options when any one supplied value is outside the list, and by options whose value comes from a preset/env var that was not added to the choices.","commonSituations":"End-user typos on enum-style options; a new valid value added to the product but not to the choices array; case sensitivity ('Red' vs 'red') because the check is a strict includes(); env var or default values that fall outside the declared choices.","solutions":["Pass one of the allowed values on the command line.","Extend the choices array to include the missing value: .choices(['red','green','blue']).","If case-insensitivity is intended, normalize via .argParser before choices, or add both cases to choices.","Give the option a sensible default so the flag can be omitted, or make it optional ([value]) so an invalid value can be avoided.","Document the allowed values in the option description so users see them in --help."],"exampleFix":"// before\nprogram.addOption(new Option('--color <c>').choices(['red', 'green']));\n// $ cli --color blue  =>  error: Allowed choices are red, green.\n\n// after (extend choices)\nprogram.addOption(new Option('--color <c>').choices(['red', 'green', 'blue']));","handlingStrategy":"try-catch","validationCode":"// Pre-scan argv against declared choices so you control the message.\nfunction validateChoices(optionName, allowed, rawValue) {\n  if (rawValue !== undefined && !allowed.includes(rawValue)) {\n    throw new Error(\n      `Invalid value '${rawValue}' for ${optionName}. Allowed: ${allowed.join(', ')}`\n    );\n  }\n}\n// usage before parse:\n// validateChoices('--color', ['red', 'green'], process.env.COLOR);","typeGuard":"function isAllowedChoice(value, choices) {\n  return Array.isArray(choices) && choices.includes(value);\n}","tryCatchPattern":"// Commander catches InvalidArgumentError itself and exits 1. To intercept it,\n// install exitOverride and catch around parse.\nconst { Command, InvalidArgumentError } = require('commander');\nconst program = new Command();\nprogram.exitOverride(); // re-throw instead of process.exit\ntry {\n  program.parseAsync(process.argv); // or parse()\n} catch (err) {\n  if (err instanceof InvalidArgumentError || err.code === 'commander.invalidArgument') {\n    console.error(`Bad input: ${err.message}`);\n    process.exit(err.exitCode ?? 1);\n  }\n  throw err;\n}","preventionTips":["Remember Commander already handles this error by default (prints + exits 1); only override when you need custom behavior.","Add new valid values to the choices array whenever the product gains a new option value.","If input is case-insensitive, normalize with argParser before choices or list all case variants.","Echo the allowed values in the option description so they appear in --help."],"tags":["validation","choices","argument","commander","user-input"],"analyzedSha":"ba6d13ddb4243e5913367734f8c159089ffe7834","analyzedAt":"2026-08-03T20:26:04.326Z","schemaVersion":2}