Search code examples
rustrust-tokio

tokio::net::TcpStream how to handle any kind of errors?


I stuck with proper handling panics in case of tokio::net::TcpStream

use tokio::*;
use tokio::{net::{ TcpStream }, io::AsyncWriteExt};

#[tokio::main]
async fn main() {
    let mut stream = TcpStream::connect("10.20.30.40:6142").await.unwrap();
    println!("created stream");

    let result = stream.write(b"hello world\n").await;
    println!("wrote to stream; success={:?}", result.is_ok());
}

or in playground

Can guru teach me how to catch these errors like

thread 'main' panicked at 'called Result::unwrap() on an Err value: Os { code: 101, kind: NetworkUnreachable, message: "Network is unreachable" }', src/main.rs:6:67


Solution

  • You'll want to change main() to handle errors, and use the ? operator instead of unwrap() to propagate them.

    type SomeResult<T> = Result<T, Box<dyn std::error::Error>>;
    
    #[tokio::main]
    async fn main() -> SomeResult<()> {
        let mut stream = TcpStream::connect("10.20.30.40:6142").await?;
        println!("created stream");
    
        let result = stream.write(b"hello world\n").await;
        println!("wrote to stream; success={:?}", result.is_ok());
    
        Ok(())
    }
    

    The last line (Ok(())) is because main() now expects a result returned. I also added an alias so you can reuse the SomeResult for other functions from which you might want to propagate errors. Here is a playground.