开发者

Which `boost::system::error_code` value should be provided when `boost::asio::ip::tcp::resolver::resolve()` fails?

开发者 https://www.devze.com 2023-04-09 08:58 出处:网络
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 pro

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 inv开发者_C百科alid argument).

What should be returned?


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!


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:

  • iterator resolve(const query & q, boost::system::error_code & ec)
  • iterator resolve(const endpoint_type & e, boost::system::error_code & ec)

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

0

精彩评论

暂无评论...
验证码 换一张
取 消