0

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

kmdreko
  • 42,554
  • 6
  • 57
  • 106
Boris Ivanov
  • 4,145
  • 1
  • 32
  • 40
  • Does this answer your question? [What is unwrap in Rust, and what is it used for?](https://stackoverflow.com/questions/36362020/what-is-unwrap-in-rust-and-what-is-it-used-for) – Jmb Feb 08 '22 at 07:34
  • Thanks for suggestion. I know what is unwrap yet got confused how to handle this. – Boris Ivanov Feb 08 '22 at 14:34
  • Have you looked at the [accepted answer](https://stackoverflow.com/a/36362163/5397009) to the suggested duplicate? It shows how to handle this: specifically don't use `unwrap` and use `match` or `if let` and/or `?` – Jmb Feb 08 '22 at 16:15
  • of course. Solution is same but question is different. I knew how unwrap works but it was not helping me. My question was about handling TcpStream connections errors. Maybe for you it is obvious but not for me. – Boris Ivanov Feb 08 '22 at 19:56
  • On Stack Overflow, "duplicate" means that the answer is the same even if the question is formulated differently. It doesn't mean that your question would be deleted, on the contrary [duplicate questions are explicitly kept to help people find the right answer by getting all of those answers in one place](https://stackoverflow.com/help/duplicates). – Jmb Feb 09 '22 at 07:25

1 Answers1

1

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.

t56k
  • 6,769
  • 9
  • 52
  • 115