Is there any crate similar to errors in Go

Is there anyway that I can recursively find out the root cause of the error in rust program. I am relatively new to rust and software development field.

Not all errors implement the Error trait, but when they do you can follow the chain of underlying errors, if any.

1 Like

Thanks for this link! This is super helpful! :tada:

1 Like

I use the anyhow crate. Then I can write functions that return errors like so:

use anyhow::Result;

pub fn connect(address: &str) -> Result<TcpStream> {
    info!("TCP/IP Connecting to {address}.");
    for _ in 1..3 {
        match TcpStream::connect(address) {
            Ok(tcp_stream) => return Ok(tcp_stream),
            Err(e) => {
                std::thread::sleep(Duration::from_secs(2));
                continue;
            }
        };
    }
    Err(anyhow::anyhow!("connect failed."))
}

Which might get called by some other function like so:

    use anyhow::Context;

    fn my_func() -> Result<()> {
       ...
        let tcp_stream = connect(&args.ssh_address).context(format!(
            "Failed to connect to SSH on {:?}",
            &args.ssh_address
        ))?;
        ...

Which in turn might be called by something that reports the error like so:

    match my_func() {
        Ok(()) => {
            info!("my_func exited OK.");
        }
        Err(e) => {
            info!("my_func FAILED:");
            for error in e.chain() {
                info!("    {error}");
            }
        }
    }

That last iterating over e.chain() thing I only discovered recently. It will print out all the chain of errors including the error messages one added with .context() on the way up the chain.

1 Like

Anyhow can also print with a backtrace when using {:?}: Error in anyhow - Rust

Just useful to know in additional to your example. :slightly_smiling_face:

1 Like