You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Boost库中获取process_error异常详情替代what()的方法

Boost.Process process_error 异常详细打印方案
  • 利用继承自std::system_error的内置方法
    process_error默认继承了std::system_error,除了what()外可以调用code()方法获取std::error_code对象,从中拆分出独立的错误码和系统原生错误描述,比单纯的what()更适合做程序逻辑判断和格式化输出:

    • pe.code().value():获取操作系统原生错误码,比如Linux下2对应ENOENT(文件/命令不存在)
    • pe.code().message():获取错误码对应的操作系统原生描述文本,内容比what()更精简准确
    • 还可以直接和标准错误枚举做比较,实现精准的错误分支处理,比如if (pe.code() == std::errc::no_such_file_or_directory)即可判断是否是命令不存在的错误,不需要解析what()的字符串内容。
  • 补充业务上下文信息
    打印异常时可以追加触发异常的commandString参数,方便快速定位是哪个命令执行失败,避免只有通用错误信息无法定位问题的情况。

  • (可选)启用Boost异常扩展信息
    如果你的项目编译时开启了Boost异常的诊断宏(BOOST_ENABLE_EXCEPTION_DEBUG),process_error还会附带源文件、行号等调试信息,可以通过boost::get_error_info接口提取这些调试信息用于开发阶段排查问题。

参考实现代码:

try {
    child c(commandString, (std_out & std_err) > pipe_stream);
} catch(const process_error &pe) {
    std::cout << "执行命令失败: " << commandString << std::endl;
    std::cout << "错误码: " << pe.code().value() << std::endl;
    std::cout << "系统错误描述: " << pe.code().message() << std::endl;
    std::cout << "异常完整描述: " << pe.what() << std::endl;
    // 错误分支判断示例
    if (pe.code() == std::errc::no_such_file_or_directory) {
        std::cout << "错误原因:当前系统中不存在该命令" << std::endl;
    }
}

内容的提问来源于stack exchange,提问作者rohit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 01:48:02