Przeglądaj źródła

Enhanced exception handling in TcpTransport::connect()

Paul-Louis Ageneau 3 lat temu
rodzic
commit
a094538711
1 zmienionych plików z 22 dodań i 18 usunięć
  1. 22 18
      src/impl/tcptransport.cpp

+ 22 - 18
src/impl/tcptransport.cpp

@@ -136,28 +136,32 @@ void TcpTransport::connect(const string &hostname, const string &service) {
 	if (getaddrinfo(hostname.c_str(), service.c_str(), &hints, &result))
 		throw std::runtime_error("Resolution failed for \"" + hostname + ":" + service + "\"");
 
-	for (auto p = result; p; p = p->ai_next) {
-		try {
-			connect(p->ai_addr, socklen_t(p->ai_addrlen));
-
-			PLOG_INFO << "Connected to " << hostname << ":" << service;
-			freeaddrinfo(result);
-			return;
-
-		} catch (const std::runtime_error &e) {
-			if (p->ai_next) {
-				PLOG_DEBUG << e.what();
-			} else {
-				PLOG_WARNING << e.what();
+	try {
+		for (auto p = result; p; p = p->ai_next) {
+			try {
+				connect(p->ai_addr, socklen_t(p->ai_addrlen));
+
+				PLOG_INFO << "Connected to " << hostname << ":" << service;
+				freeaddrinfo(result);
+				return;
+
+			} catch (const std::runtime_error &e) {
+				if (p->ai_next) {
+					PLOG_DEBUG << e.what();
+				} else {
+					PLOG_WARNING << e.what();
+				}
 			}
 		}
-	}
 
-	freeaddrinfo(result);
+		std::ostringstream msg;
+		msg << "Connection to " << hostname << ":" << service << " failed";
+		throw std::runtime_error(msg.str());
 
-	std::ostringstream msg;
-	msg << "Connection to " << hostname << ":" << service << " failed";
-	throw std::runtime_error(msg.str());
+	} catch (...) {
+		freeaddrinfo(result);
+		throw;
+	}
 }
 
 void TcpTransport::connect(const sockaddr *addr, socklen_t addrlen) {