How can I check if the error from try_bind_with_graceful_shutdown
is std::io::ErrorKind::AddrInUse
?
问问题
87 次
1 回答
1
如果您warp
从存储库(而不是 crates.io)使用,您可以结合Error::source()
使用Error::downcast_ref()
来做您想做的事情:
let hello = warp::path!("hello" / String)
.map(|name| format!("Hello, {}!", name));
match warp::serve(hello).try_bind_with_graceful_shutdown(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 8081), std::future::pending()) {
Ok((_, future)) => future.await,
Err(error) => {
use std::error::Error;
let mut current_error: &dyn Error = &error;
let is_because_of_addr_in_use = loop {
// get source of the error...
current_error = match current_error.source() {
// if there is one, continue
Some(source) => source,
// else, this error is not because of AddrInUse
None => break false
};
//if the source is of type `std::io::Error`
if let Some(io_error) = current_error.downcast_ref::<std::io::Error>() {
break io_error.kind() == std::io::ErrorKind::AddrInUse;
}
};
println!("Failed. is_because_of_addr_in_use == {}", is_because_of_addr_in_use);
}
};
Failed. is_because_of_addr_in_use == true
当且仅当由于它已在使用中而warp
未能绑定到时,才会打印。SocketAddr
请注意,这不适用于已发布的版本,warp
因为实现的拉取请求Error::source
warp::Error
尚未发布。如果您使用的warp
是.Debug
Display
warp::Error
于 2021-08-31T17:21:39.637 回答