Trait eyre::ContextCompat
source · pub trait ContextCompat<T>: Sealed {
// Required methods
fn context<D>(self, msg: D) -> Result<T, Report>
where D: Display + Send + Sync + 'static;
fn with_context<D, F>(self, f: F) -> Result<T, Report>
where D: Display + Send + Sync + 'static,
F: FnOnce() -> D;
fn wrap_err<D>(self, msg: D) -> Result<T, Report>
where D: Display + Send + Sync + 'static;
fn wrap_err_with<D, F>(self, f: F) -> Result<T, Report>
where D: Display + Send + Sync + 'static,
F: FnOnce() -> D;
}
Expand description
Provides the context
method for Option
when porting from anyhow
This trait is sealed and cannot be implemented for types outside of
eyre
.
§Why Doesn’t Eyre
impl WrapErr
for Option
?
eyre
doesn’t impl WrapErr
for Option
because wrap_err
implies that you’re creating a
new error that saves the previous error as its source
. Calling wrap_err
on an Option
is
meaningless because there is no source error. anyhow
avoids this issue by using a different
mental model where you’re adding “context” to an error, though this not a mental model for
error handling that eyre
agrees with.
Instead, eyre
encourages users to think of each error as distinct, where the previous error
is the context being saved by the new error, which is backwards compared to anyhow’s model. In
this model you’re encouraged to use combinators provided by std
for Option
to convert an
option to a Result
§Example
Instead of:
use eyre::ContextCompat;
fn get_thing(mut things: impl Iterator<Item = u32>) -> eyre::Result<u32> {
things
.find(|&thing| thing == 42)
.context("the thing wasnt in the list")
}
We encourage you to use this:
use eyre::eyre;
fn get_thing(mut things: impl Iterator<Item = u32>) -> eyre::Result<u32> {
things
.find(|&thing| thing == 42)
.ok_or_else(|| eyre!("the thing wasnt in the list"))
}
Required Methods§
sourcefn context<D>(self, msg: D) -> Result<T, Report>
fn context<D>(self, msg: D) -> Result<T, Report>
Compatibility version of wrap_err
for creating new errors with new source on Option
when porting from anyhow
sourcefn with_context<D, F>(self, f: F) -> Result<T, Report>
fn with_context<D, F>(self, f: F) -> Result<T, Report>
Compatibility version of wrap_err_with
for creating new errors with new source on Option
when porting from anyhow