Skip to content

Commit

Permalink
issue launchbadge#2821 Update error handling logic when opening a TCP…
Browse files Browse the repository at this point in the history
… connection

This commit updates the error handling logic in the `connect_tcp` function. Previously, the function would panic if the hostname did not resolve to at least one address.

The updated logic attempts to establish a TCP connection for each address that the hostname resolves to. If it fails to connect to any of the addresses, it will return the last encountered error. If the hostname doesn't resolve to any addresses, the function returns a custom error message stating "Hostname did not resolve to any addresses".
  • Loading branch information
anupj committed Oct 18, 2023
1 parent b85b723 commit a571e93
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions sqlx-core/src/net/socket/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,15 +205,28 @@ pub async fn connect_tcp<Ws: WithSocket>(
use async_std::net::ToSocketAddrs;
use std::net::TcpStream;

let socket_addr = (host, port)
.to_socket_addrs()
.await?
.next()
.expect("BUG: to_socket_addrs() should have returned at least one result");
let mut last_err = None;

let stream = Async::<TcpStream>::connect(socket_addr).await?;
// Loop through all the Socket Addresses that the hostname resolves to
for socket_addr in (host, port).to_socket_addrs().await? {
match Async::<TcpStream>::connect(socket_addr).await {
Ok(stream) => return Ok(with_socket.with_socket(stream)),
Err(e) => last_err = Some(e),
}
}

return Ok(with_socket.with_socket(stream));
// If we reach this point, it means we failed to connect to any of the addresses.
// Return the last error we encountered, or a custom error if the hostname didn't resolve to any address.
match last_err {
Some(err) => return Err(err.into()),
None => {
return Err(io::Error::new(
io::ErrorKind::AddrNotAvailable,
"Hostname did not resolve to any addresses",
)
.into())
}
}
}

#[cfg(not(feature = "_rt-async-std"))]
Expand Down

0 comments on commit a571e93

Please sign in to comment.