ArgumentException should not be sent immediately
Created by: Arcesilas
Throwing exceptions immediately when an argument is unexpected or missing when processing arguments list prevent from using valuable options like --help
or --verbose
, as they have not been processed and therefore are not available when handling the exception.
To observe, just take the example file provided in the documentation and just make this change:
try {
$getOpt->process();
} catch (unexpected | Missing $exception) {
// catch missing exceptions if help is requested
if (!$getOpt->getOption('help')) {
throw $exception;
} else {
echo 'Help option provided'.PHP_EOL;
}
}
Now call the script with: php example.php -p --help
The exception will always be thrown and the text Help option provided
will not be displayed, despite we provided the help option.
Note that this does not happen if we pass the help option first: php example.php --help -p
To prevent this from happening, exceptions should be stored somewhere (Symfony uses an ExceptionBag if I'm correct). After processing the arguments list is done, the exceptions can then be checked and handled appropriately. This allows to use options to adjust error handling (verbose mode for example).
I may provide with some PR if you're interested, to have something concrete to discuss.