问题很简单,但我不知道该怎么做。我想获取 system_error,并从那里获取具体的错误代码。我在错误中有这样的东西:
Dynamic exception type: boost::exception_detail::clone_impl<boost::exception_detail::current_exception_std_exception_wrapper<std::runtime_error> >
std::exception::what:
boost::system::system_error
我可以直接捕获 boost::exception
但不能捕获 std::runtime_error
或 boost::system_error
:
try {
this->service_.run();
}
catch (boost::system::system_error const & e) {
i_->playerLog->info("Exiting with system error. Error code: {} -- What: {}", e.code().value(),
e.what());
}
catch (boost::exception const & e) {
i_->playerLog->info("Exiting with boost exception: {}", boost::diagnostic_information(e));
}
我的代码将进入 boost::exception 子句,但绝不会进入 system_error 或 runtime_erro
最佳答案
这应该没问题:
#include <boost/asio.hpp>
#include <iostream>
int main() {
try {
using namespace boost::asio;
io_service svc;
ip::tcp::acceptor a(svc);
a.open(ip::tcp::v4());
a.bind({{}, 22}); // error, need admin privs
} catch(boost::system::system_error const& e) {
std::cout << e.what() << ": " << e.code() << " - " << e.code().message() << "\n";
}
}
打印
bind: Permission denied: system:13 - Permission denied
如果不是,通常您会混合使用类型信息不匹配的动态加载库。
奖金
为了完整性,使用更详细的异常信息进行了测试: Live On Coliru
关于c++ - 如何从 boost 异常中正确解包错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48357249/