2 ms·
I think that it's reasonable to look at two features designed to solve similar problems, and think they look similar. And yeah, anyhow feels closer to an except
by steveklabnik 2y ago
I think that it's reasonable to look at two features designed to solve similar problems, and think they look similar. And yeah, anyhow feels closer to an exception. There's some differences though; you don't have to use anyhow, so in some senses, Rust's system here has more flexibility overall. Another is that anyhow gives you a more "semantic" backtrace by default. Here's what I mean: Consider this program:
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.
- protomolecule 2y agoYep, semantic backtrace is very handy when you need the user to understand the error and fix input data.