7

I want to return a boost::system::error_code indicationg whether a host/service could be resolved or not. There might be multiple reasons why a host/service look-up failed (e.g. network connection problems or an invalid argument).

What should be returned?

Sam Miller
  • 23,808
  • 4
  • 67
  • 87
0xbadf00d
  • 17,405
  • 15
  • 67
  • 107

2 Answers2

5

You have to come up with error code and category in order to create error_code object. Here is an example, assuming that error is due to another host refusing connection:

error_code ec (errc::connection_refused, system_category());
return ec;

You can also pass errno value as error code when using system category. For example:

#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");
    }
}

Unfortunately, this library is poorly documented, so I can recommend you to look into header files to figure things out. The code is fairly simple and straight forward there.

Just in case your compiler supports C++11 and you are willing to use it, this functionality made it into standard. As far as I know gcc 4.6.1 has it already. Here is a simple example:

#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");
}

Generally, libraries pass error_code object around if there is no need to throw and use system_error to throw an exception describing system failures. Another reason to use error_code without exceptions is when you need to signal the error across different threads. But C++11 has a solution for propagating exceptions across threads.

Hope it helps!

Community
  • 1
  • 1
2

It's impossible to get this right from outside resolve(). But you can get it to do it for you, by using one of the overloads that takes an error_code& as an out-parameter:

and then return the error_code it sets. I trust that this will wrap up errno or h_errno as appropriate.

zwol
  • 135,547
  • 38
  • 252
  • 361