【问题标题】:Which `boost::system::error_code` value should be provided when `boost::asio::ip::tcp::resolver::resolve()` fails?当 `boost::asio::ip::tcp::resolver::resolve()` 失败时,应该提供哪个 `boost::system::error_code` 值?
【发布时间】:2011-11-28 13:40:22
【问题描述】:

我想返回一个boost::system::error_code 指示是否可以解析主机/服务。主机/服务查找失败的原因可能有多种(例如网络连接问题或无效参数)。

应该返回什么?

【问题讨论】:

    标签: c++ boost boost-asio


    【解决方案1】:

    您必须提供错误代码和类别才能创建error_code 对象。这是一个示例,假设错误是由于另一个主机拒绝连接:

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

    您还可以在使用系统类别时将errno 值作为错误代码传递。例如:

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

    不幸的是,这个库很糟糕documented,所以我可以建议你查看header files 来解决问题。那里的代码相当简单直接。

    万一您的编译器支持 C++11 并且您愿意使用它,此功能使其成为标准。据我所知 gcc 4.6.1 已经有了。这是一个简单的例子:

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

    通常,如果不需要抛出,库会传递error_code 对象,并使用system_error 抛出描述系统故障的异常。无例外地使用error_code 的另一个原因是当您需要在不同线程之间发出错误信号时。但是 C++11 有a solution for propagating exceptions across threads

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      不可能从外部resolve() 获得此权利。但是您可以通过使用将error_code&amp; 作为输出参数的重载之一来为您执行此操作:

      然后返回它设置的error_code。我相信这会酌情结束errnoh_errno

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-14
        • 1970-01-01
        • 2021-05-21
        • 1970-01-01
        相关资源
        最近更新 更多