Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to countercheck a Boost Error Code appropriately?

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?

like image 939
Toby Avatar asked Feb 10 '12 08:02

Toby


3 Answers

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;
}
like image 158
Scott Langham Avatar answered Oct 22 '22 03:10

Scott Langham


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

like image 21
Nick Avatar answered Oct 22 '22 02:10

Nick


You can use a default constructed error_code:

if( error == boost::system::error_code() )
like image 25
syffinx Avatar answered Oct 22 '22 02:10

syffinx