Tob*_*oby 15 c++ error-handling boost boost-asio
我有一个绑定到a的回调函数boost::asio::deadline_timer.现在,当取消定时器或它到期时,将调用该函数.由于我需要区分这两种情况,我需要检查传递的错误代码.基本代码如下:
void CameraCommand::handleTimeout(const boost::system::error_code& error)
{
std::cout << "\nError: " << error.message() << "\n";
return;
}
Run Code Online (Sandbox Code Playgroud)
现在当调用处理程序因为计时器到期时错误代码是Success,当取消计时器时错误代码是Operation canceled.
现在我的问题是,如何正确检查发生了什么?
建议1:
if( error.message() == "Success" )
{
// Timer expired
}
else
{
// Timer cancelled
}
Run Code Online (Sandbox Code Playgroud)
建议2:
if( error.value() == 0 )
{
// Timer expired
}
else
{
// Timer cancelled
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是 - 有没有办法比较错误本身而不是价值或字符串?有点像(现在这个)
if ( error == boost::system::error::types::success )
Run Code Online (Sandbox Code Playgroud)
因为我不喜欢第一个建议是我需要创建一个字符串只是为了检查,这在我看来是有点不必要的.第二种方式有一个弱点,我需要查找所有错误代码,如果我想检查其他东西?那么有没有任何枚举或方法来检查错误或我有两种建议的方式之一?
Sco*_*ham 20
查看文档,您可以使用枚举值:
switch( error.value() )
{
case boost::system::errc::success:
{
}
break;
case boost::system::errc::operation_canceled:
{
// Timer cancelled
}
break;
default:
{
// Assert unexpected case
}
break;
}
Run Code Online (Sandbox Code Playgroud)
Nic*_*ick 13
你可以使用一个布尔强制转换:
if ( error )
{
// Timer has been cancelled - or some other error. If you just want information
// about the error then you can output the message() of the error.
}
else
{
...
}
Run Code Online (Sandbox Code Playgroud)
boost::error_code有一个布尔运算符,请看这里:http://www.boost.org/doc/libs/1_48_0/libs/system/doc/reference.html#Class-error_code