将提升 (ASIO) 错误消息转换为自然语言



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

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

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

您可能应该只使用system::error_code::message()

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

运算符<<必须适用于所有类别 - 这是开放式设计的,因此这就是仅显示类别名称的原因。

我在项目中使用这样的东西来使错误报告更具信息性:

#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

最新更新