I have an indexer, which needs to be configured first – requires API credentials.
When I run in a reindex command in CLI: $ bin/magento indexer:reindex my_reindexer_name
and the API credentials are not set, I want to display an error / warning message telling the user to configure his credentials. Currently I'm doing it like this:
if ($wrongCredentials) {
$errorMessage = 'You need to configure your credentials';
if (php_sapi_name() === 'cli') {
throw new \Exception($errorMessage);
}
$this->messageManager->addErrorMessage($errorMessage);
return;
}
The issue with this approach is that when the Magento is installed from CLI (via $ bin/magento setup:install ...
), the Magento tries to reindex the data, the Exception is thrown (of course, API credentials are not set yet) – so the installation crashes. But I don't want to break the install, simply displaying the message is fine.
When I replace throw new \Exception(...);
by simple echo $errorMessage
(which works), Magento Marketplace refuses the extension from technical review (bad echo
placement).
When I remove the CLI condition completely, $messageManager
won't display the error message in CLI.
So the question is – how correctly display the error message in CLI without breaking the installation? Thanks!
Best Answer
If you are inside the
execute
method why don't you put the error message inside$output->writeln($errorMessage);
? Where you have access to theOutputInterface
Update:
Inject
\Symfony\Component\Console\Output\ConsoleOutput $output
via constructor to access$this->output->writeln($errorMessage);
inside your method.