我想返回一个boost::system::error_code
指示是否可以解析主机/服务。主机/服务查找失败的原因可能有多种(例如,网络连接问题或无效参数)。当boost :: asio :: ip :: tcp :: resolver :: resolve()失败时,应该提供哪个`boost :: system :: error_code`值?
应该返回什么?
我想返回一个boost::system::error_code
指示是否可以解析主机/服务。主机/服务查找失败的原因可能有多种(例如,网络连接问题或无效参数)。当boost :: asio :: ip :: tcp :: resolver :: resolve()失败时,应该提供哪个`boost :: system :: error_code`值?
应该返回什么?
这是不可能从外部resolve()
得到这个权利。但是你可以让它为你做,通过使用需要一个error_code&
作为out参数的重载之一:
您必须拿出错误代码和类别才能创建error_code
对象。下面是一个例子,假设错误是由于另一主机拒绝连接:
error_code ec (errc::connection_refused, system_category());
return ec;
也可以使用系统类别时传递errno
值作为错误代码。例如:
#include <fstream>
#include <cerrno>
#include <boost/system/system_error.hpp>
void foo()
{
ifstream file ("test.txt");
if (!file.is_open())
{
int err_code = errno;
boost::system::error_code ec (err_code
, boost::system::system_category());
throw boost::system::system_error (ec, "cannot open file");
}
}
不幸的是,这个库是很差documented,所以我建议你看看header files理出头绪。代码非常简单直接。
为了防止您的编译器支持C++ 11并且您愿意使用它,该功能使其成为标准。据我所知gcc 4.6.1已经有了。下面是一个简单的例子:
#include <cerrno>
#include <system_error>
std::error_code
SystemError::getLastError()
{
int err_code = errno;
return std::error_code (err_code, std::system_category());
}
void foo()
{
throw std::system_error (getLastError(), "something went wrong");
}
一般来说,图书馆通过周围error_code
对象,如果没有必要扔掉,用system_error
扔描述系统故障异常。使用error_code
而没有例外的另一个原因是当你需要在不同线程间发出错误信号时。但是C++ 11有a solution for propagating exceptions across threads。
希望它能帮助!