将 boost (asio) 错误消息翻译成自然语言
Translating boost (asio) error messages to natural language
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
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