At the moment, I'm using Boost Asio in order to connect to a server via TCP.
I use a conditional case to decide if the application has to start or not a connection with the server; it works great but the problem is that if I try to connect to the server when the server is down then the application crash giving this error:
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >'
what(): Connection refused
This is the code I'm using:
case CONNECTION:
// Connect to the server
using boost::asio::ip::tcp;
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), server, boost::lexical_cast<string>(porta));
tcp::resolver::iterator iterator = resolver.resolve(query);
tcp::socket s(io_service);
s.connect(*iterator);
I'd like to keep alive my application with its normal behavior and only prompt a warning about the connection failed.
How can I handle this exception?
You should use try ... catch
blocks. They work this way :
try
{
s.connect(*iterator);
}
catch (boost::system::system_error const& e)
{
std::cout << "Warning: could not connect : " << e.what() << std::endl;
}
According to documentation here, on failure connect
throws boost::system::system_error
. So you need to wrap around your code in a try...catch
block and catch the above mentioned exception. Or if you don't want to use the exceptions you can use the other overload described here which returns an error code on error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With