Thanks for chiming in.
When I looked at anyhow, I remember thinking that it's just a way to emulate in Rust the kind of error propagation that C++ has with exceptions, but manually with ?.
What's your take on this?
When I looked at anyhow, I remember thinking that it's just a way to emulate in Rust the kind of error propagation that C++ has with exceptions, but manually with ?.
What's your take on this?
use anyhow::Result;
use anyhow::bail;
fn main() -> Result<()> {
foo()?;
Ok(())
}
fn foo() -> Result<()> {
bar()?;
Ok(())
}
fn bar() -> Result<()> {
bail!("oh no");
}
When you run this, you'll see Error: oh no
We don't get a stacktrace, we get our error.Whenever you want to insert something into this backtrace, you can:
use anyhow::bail;
use anyhow::Context;
use anyhow::Result;
fn main() -> Result<()> {
foo()?;
Ok(())
}
fn foo() -> Result<()> {
bar().context("couldn't bar")?;
Ok(())
}
fn bar() -> Result<()> {
bail!("oh no");
}
Running this, you instead get Error: couldn't bar
Caused by:
oh no
And if we add some context to foo: Error: was trying to foo
Caused by:
0: couldn't bar
1: oh no
I find this to be a lot nicer than a stacktrace. And if you want to get a stacktrace, you can do so by setting the standard environment variable.