![](/img/trans.png)
[英]boost::asio::ip::tcp::resolver::resolve() blocks forever
[英]Which `boost::system::error_code` value should be provided when `boost::asio::ip::tcp::resolver::resolve()` fails?
我想返回一個boost::system::error_code
指示是否可以解析主機/服務。 主機/服務查找失敗可能有多種原因(例如,網絡連接問題或無效參數)。
應該歸還什么?
您必須提供錯誤代碼和類別才能創建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");
}
}
不幸的是,這個庫文檔很少,所以我建議你查看頭文件來解決問題。 代碼相當簡單直接。
如果您的編譯器支持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");
}
通常,如果不需要拋出並使用system_error
拋出描述系統故障的異常,庫會傳遞error_code
對象。 使用error_code
而無異常的另一個原因是當您需要跨不同線程發出錯誤信號時。 但是C ++ 11有一個跨線程傳播異常的解決方案 。
希望能幫助到你!
從外面resolve()
這是不可能的。 但是你可以通過使用帶有error_code&
out參數的重載之一來讓它為你做到:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.