c++ - 运行无效命令 C++ 时优雅退出
问题描述
我正在使用 boost 从我的应用程序运行命令行命令。我正在使用以下已封装到辅助函数中的代码:
tuple<string, int> Utility::RunCommand(const string& arguments) const
{
string response;
int exitCode;
try
{
ipstream iStream;
auto childProcess = child(arguments, std_out > iStream);
string line;
while (getline(iStream, line) && !line.empty())
{
response += line;
}
childProcess.wait();
exitCode = childProcess.exit_code();
}
catch (...)
{
// log error
throw;
}
return make_tuple(response, exitCode);
}
现在我有一个只能在具有某些属性的机器上运行的命令。此方法返回这些机器上的预期响应和错误代码。在其他机器上,它会引发异常。
我尝试在应该失败的机器上手动运行该命令,并返回以下输出:
POWERSHELL
PS C:\Users\xyz> dummy-cmd
dummy-cmd : The term 'dummy-cmd' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ dummy-cmd
+ ~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (dummy-cmd:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
COMMAND PROMPT
C:\Users\xyz>dummy-cmd
'dummy-cmd' is not recognized as an internal or external command,
operable program or batch file.
如何使其运行以返回非零错误代码而不是引发异常?
解决方案
这就是您的catch
子句的用途,用于处理异常。它不必重新抛出它们:
tuple<string, int> Utility::RunCommand(const string& arguments) const
{
string response;
int exitCode;
try
{
ipstream iStream;
auto childProcess = child(arguments, std_out > iStream);
string line;
while (getline(iStream, line) && !line.empty())
{
response += line;
}
childProcess.wait();
exitCode = childProcess.exit_code();
}
catch (PlatformNotSupportedException& e)
{
std::cerr << "That operation is not supported on this platform." << std::endl;
exit(1);
}
catch (...)
{
std::cerr << "Unspecified error occurred." << std::endl;
exit(1); // give nonzero exit code
//throw; // take out this
}
return make_tuple(response, exitCode);
}
推荐阅读
- uuid - TypeORM 生成奇怪的“无版本”UUID
- java - 从远程存储库下载依赖项而不修改 pom.xml
- javascript - 如何获取 2 个独立按钮的标签中的值?
- cypress - 禁用按钮元素的赛普拉斯条件语句
- post - 无法将 GraphQL 自定义类型作为 Postman 变量
- google-app-engine - Google App Engine 将数据流式传输到 Bigquery:GCP 架构
- python - pandas:检查数据框中是否存在 2 列
- java-8 - 无法返回单声道
- python - 如何将抓取的数据存储到列表中,然后存储到数据框中
- pull-request - Bamboo:创建拉取请求时创建“计划分支”,但按目标分支过滤