I have a callback function which is bound to a boost::asio::deadline_timer
. Now the function is called when the timer is cancelled or it expires. Since I need to distinguish between this two cases I need to check the passed Error code. The basic code would be like this:
void CameraCommand::handleTimeout(const boost::system::error_code& error)
{
std::cout << "\nError: " << error.message() << "\n";
return;
}
Now when the Handler is called because the timer expired the error code is Success
, when the timer is cancelled the error code is Operation canceled
.
Now my question would be, how to appropriately check what happened?
Suggestion 1:
if( error.message() == "Success" )
{
// Timer expired
}
else
{
// Timer cancelled
}
Suggestion 2:
if( error.value() == 0 )
{
// Timer expired
}
else
{
// Timer cancelled
}
Now my question is - is there any way to compare the error byitself and not by value or by string? Something like ( this is made up now )
if ( error == boost::system::error::types::success )
Because what I don't like about the first suggestion is that I need to create a string just for check, which is kinda unnecessary in my opinion. The second way has the disadvantge that I need to look up all the error codes if I want to check for something other? So are there any enums or ways to check for the error or do I have one of the two suggested ways?
Looking at the documentation, you can use the enum values:
switch( error.value() )
{
case boost::system::errc::success:
{
}
break;
case boost::system::errc::operation_canceled:
{
// Timer cancelled
}
break;
default:
{
// Assert unexpected case
}
break;
}
You can just use a boolean cast:
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
{
...
}
boost::error_code
has a boolean operator for this, have a look here: http://www.boost.org/doc/libs/1_48_0/libs/system/doc/reference.html#Class-error_code
You can use a default constructed error_code:
if( error == boost::system::error_code() )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With