Skip to main content

ErrorContext

Trait ErrorContext 

Source
pub trait ErrorContext {
    type Output;

    // Required methods
    fn context(self, consequent: impl IntoError) -> Self::Output;
    fn with_context<E: IntoError>(
        self,
        consequent: impl FnOnce() -> E,
    ) -> Self::Output;
}
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 jiff, which borrowed it from anyhow.

Required Associated Types§

Required Methods§

Source

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

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::Output

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.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<T, E> ErrorContext for Result<T, E>
where E: StdError + Send + Sync + 'static,

Source§

type Output = Result<T, Error>

Source§

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

Source§

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

Implementors§