Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid the program exit after Connection Refused with Boost Asio and C/C++

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?

like image 565
Marcus Barnet Avatar asked Jun 06 '11 10:06

Marcus Barnet


2 Answers

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;
}
like image 99
user703016 Avatar answered Sep 22 '22 15:09

user703016


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.

like image 29
Asha Avatar answered Sep 21 '22 15:09

Asha