jiff::error

Trait ErrorContext

Source
pub(crate) trait ErrorContext {
    // Required methods
    fn context(self, consequent: impl IntoError) -> Self;
    fn with_context<E: IntoError>(self, consequent: impl FnOnce() -> E) -> Self;
}
Expand description

A trait for contextualizing error values.

This makes it easy to contextualize either Error or Result<T, Error>. Specifically, in the latter case, it absolves one of the need to call map_err everywhere one wants to add context to an error.

This trick was borrowed from anyhow.

Required Methods§

Source

fn context(self, consequent: impl IntoError) -> Self

Contextualize the given consequent error with this (self) error as the cause.

This is equivalent to saying that “consequent is caused by self.”

Note that if an Error is given for kind, then this panics if it has a cause. (Because the cause would otherwise be dropped. An error causal chain is just a linked list, not a tree.)

Source

fn with_context<E: IntoError>(self, consequent: impl FnOnce() -> E) -> Self

Like context, but hides error construction within a closure.

This is useful if the creation of the consequent error is not otherwise guarded and when error construction is potentially “costly” (i.e., it allocates). The closure avoids paying the cost of contextual error creation in the happy path.

Usually this only makes sense to use on a Result<T, Error>, otherwise the closure is just executed immediately anyway.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T> ErrorContext for Result<T, Error>

Source§

fn context(self, consequent: impl IntoError) -> Result<T, Error>

Source§

fn with_context<E: IntoError>( self, consequent: impl FnOnce() -> E, ) -> Result<T, Error>

Implementors§