How to avoid program exit after failure in connection with Boost Asio and C / C ++

I am currently using Boost Asio to connect to the server via TCP.

I use a conditional case to decide if the application should start or not connect to the server; It works fine, but the problem is that if I try to connect to the server when the server is down, the application error gives 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 would like to save my application with its normal behavior and only raise a connection failure warning.

How can I handle this exception?

+6
source share
2 answers

You should use try ... catch blocks. They work as follows:

 try { s.connect(*iterator); } catch (boost::system::system_error const& e) { std::cout << "Warning: could not connect : " << e.what() << std::endl; } 
+7
source

According to the documentation here , when connect throws boost::system::system_error . Therefore, you need to wrap the code in a try...catch and catch the above exception. Or if you do not want to use exceptions, you can use another overload, described here here , which returns an error code when an error occurs.

+6
source

Source: https://habr.com/ru/post/889857/


All Articles