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.
Thanks for this link! This is super helpful!
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.
Anyhow can also print with a backtrace when using {:?}
: Error in anyhow - Rust
Just useful to know in additional to your example.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.