Boris Ivanov
Boris Ivanov

Reputation: 4254

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

Upvotes: 0

Views: 1085

Answers (1)

t56k
t56k

Reputation: 6981

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.

Upvotes: 1

Related Questions