shepmaster / snafu

Easily assign underlying errors into domain-specific errors while adding context
https://docs.rs/snafu/
Apache License 2.0
1.39k stars 60 forks source link

Is it possible to avoid manually capturing a backtrace when variant has no `source` error? #457

Closed casey closed 2 months ago

casey commented 2 months ago

Using this error type as an example:

#[derive(Snafu)]
enum Error {
  Foo { backtrace: Backtrace, source: std::io::Error },
  Bar { backtrace: Backtrace },
}

When using a context selector, it's possible to automatically capture a backtrace:

read_file().context(FooSnafu)?;

Is it possible to avoid manually capturing a backtrace when there is no source error?

if !condition {
  // currently I do this:
  return Err(Error::Bar { backtrace: Backtrace });

  // but would like to be able to do something like this:
  return Err(BarSnafu.into());
}

PS As always, thanks for snafu, it's rad.

shepmaster commented 2 months ago

Yep. See the docs (search for "Otherwise, the context selector will have the inherent methods")

TL;DR: try this:

if !condition {
  return BarSnafu.fail();
}

Or use ensure:

ensure!(condition, BarSnafu);
casey commented 2 months ago

Awesome, that's perfect. Thank you!