Cmdline: use exceptions for control flow

This is generally frowned upon but it makes this code 10x cleaner.
We handle commandLine usage msg printing by using exceptions for
control flow. This allows us to centralize the logic for killing
the Mind threads in one place. At least with respect to printing
the usage msg.
This commit is contained in:
2025-08-13 09:43:34 -04:00
parent 7bee9b07ae
commit b6b2ce7ada
3 changed files with 86 additions and 32 deletions
+27 -26
View File
@@ -8,6 +8,7 @@
#include <marionette/marionette.h>
#include <salmanoff.h>
#include <boost/asio/signal_set.hpp>
#include <typeinfo>
namespace smo {
@@ -55,34 +56,15 @@ void ComponentThread::marionetteMain(ComponentThread& self)
std::cout << __func__ << ": " << PACKAGE_NAME << " " << PACKAGE_VERSION
<< std::endl;
try {
options.parseArguments(
crtCommandLineArgs.argc, crtCommandLineArgs.argv,
crtCommandLineArgs.envp);
options.parseArguments(
crtCommandLineArgs.argc, crtCommandLineArgs.argv,
crtCommandLineArgs.envp);
std::cout << __func__ << ": " << options.stringifyOptions()
<< std::endl;
}
catch (const std::invalid_argument& e)
{
std::cerr << __func__ << ": Exception occurred: " << e.what()
<< '\n';
std::cout << __func__ << ": " << options.stringifyOptions()
<< std::endl;
options.printUsage = true;
mrntt::exitCode = EXIT_FAILURE;
}
if (options.printUsage)
{
/* We could make RAII guard classes to always shutdown the mind
* threads properly in these pre-event loop situations.
*/
mind.finalizeReq([]{
mrntt::mrntt->getIoService().stop();
});
self.getIoService().reset();
self.getIoService().run();
return;
if (options.printUsage) {
throw JustPrintUsageNoError(options);
}
self.getIoService().post([]()
@@ -130,6 +112,25 @@ void ComponentThread::marionetteMain(ComponentThread& self)
std::cout << __func__ << ": Exited event loop" << "\n";
shutdownSalmanoff();
}
catch (const OptionParser::Exception& e)
{
std::ostream &out = std::cout;
std::string outUsageMsg;
if (typeid(e) == typeid(OptionsParserError))
{
mrntt::exitCode = EXIT_FAILURE;
outUsageMsg = std::string(__func__) + ": ";
}
out << outUsageMsg << e.what() << std::endl;
mind.finalizeReq([]{
mrntt::mrntt->getIoService().stop();
});
self.getIoService().reset();
self.getIoService().run();
return;
}
catch (const std::exception& e)
{
std::cerr << __func__ << ": Exception occurred: " << e.what()