【问题标题】:Translating boost (asio) error messages to natural language将 boost (asio) 错误消息翻译成自然语言
【发布时间】:2018-12-25 21:55:37
【问题描述】:

boost::system::error_code 有一个转换为字符串的函数,可以方便地给我一些打印的东西。不幸的是,它通常类似于“system:9”,并不太有用。从阅读来源看来,数字是在枚举中建立的,因此我可以测试特定条件,但不太容易知道遇到了哪种条件。

似乎将error_condition.value() 传递给perror() / strerror() 恰好可以工作,但我没有找到说明这是可以保证的文档。我错过了吗?我应该更加怀疑吗?

我很怀疑,主要是因为我不明白为什么operator<<() 打印的字符串不只使用strerror(),如果它保证有效的话。

【问题讨论】:

    标签: c++ boost c++14 boost-asio


    【解决方案1】:

    你应该只使用system::error_code::message():

    void foo(boost::system::error_code ec) {
         std::cout << "foo called (" << ec.message() << ")\n";
    }
    

    运算符

    【讨论】:

      【解决方案2】:

      我在我的项目中使用这样的东西来使错误报告更加丰富:

      #include <boost/system/error_code.hpp>
      #include <ostream>
      #include <iostream>
      
      
      struct report
      {
          report(boost::system::error_code ec) : ec(ec) {}
      
          void operator()(std::ostream& os) const
          {
              os << ec.category().name() << " : " << ec.value() << " : " << ec.message();
          }
      
          boost::system::error_code ec;
      
          friend std::ostream& operator<<(std::ostream& os, report rep)
          {
              rep(os);
              return os;
          }
      };
      
      
      
      int main()
      {
          auto ec = boost::system::error_code(EINTR, boost::system::system_category());
          std::cout << "the error is : " << report(ec) << '\n';
      }
      

      示例输出:

      the error is : system : 4 : Interrupted system call
      

      http://coliru.stacked-crooked.com/a/91c02689f2ca74b2

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-01
        • 1970-01-01
        • 2010-09-16
        • 2021-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多