WithContext

Trait WithContext 

Source
pub trait WithContext<T, E> {
    // Required methods
    fn with_err_context(self, reason: impl ToString) -> Result<T, ErrorMessage>;
    fn with_dyn_err_context(
        self,
        reason: impl FnOnce() -> String,
    ) -> Result<T, ErrorMessage>;
}
Expand description

WithContext is implemented for Result and Option see with_err_context and with_dyn_err_context for more details

Required Methods§

Source

fn with_err_context(self, reason: impl ToString) -> Result<T, ErrorMessage>

Convert an Option<T> or Result<T,_> into Result<T, ErrorMessage>

Example usage for Option<T>

fn produce_none() -> Option<()> { None }
produce_none()
    .with_err_context("Something went wrong in function 'produce_none'");

prints

Something went wrong in function 'produce_none'

Example usage for Result<T,_>

fn produce_err() -> Result<(), io::Error> { Err(io::ErrorKind::UnexpectedEof.into())}
produce_err()
    .with_err_context("Something went wrong in function 'produce_err'");

prints

Something went wrong in function 'produce_err'
 caused by: Kind(UnexpectedEof)
Source

fn with_dyn_err_context( self, reason: impl FnOnce() -> String, ) -> Result<T, ErrorMessage>

Convert an Option<T> or Result<T,_> into Result<T, ErrorMessage>

Example usage for Option<T>

use errors_with_context::prelude::*;
fn produce_none() -> Option<()> { None }
let variable = "Test";
produce_none()
    .with_dyn_err_context(|| format!("Something went wrong in function 'produce_none'. Extra info: {variable}"));

prints

Something went wrong in function 'produce_err'. Extra info: Test
 caused by: Kind(UnexpectedEof)

and

Something went wrong in function 'produce_none'. Extra info: Test

Example usage for Result<T,_>

use errors_with_context::prelude::*;
fn produce_err() -> Result<(), io::Error> { Err(io::ErrorKind::UnexpectedEof.into())}
let variable = "Test";
produce_err()
    .with_dyn_err_context(|| format!("Something went wrong in function 'produce_err'. Extra info: {variable}"));

prints

Something went wrong in function 'produce_err'
 caused by: Kind(UnexpectedEof)

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> WithContext<T, Infallible> for Option<T>

Source§

fn with_err_context(self, context: impl ToString) -> Result<T, ErrorMessage>

Source§

fn with_dyn_err_context( self, context: impl FnOnce() -> String, ) -> Result<T, ErrorMessage>

Source§

impl<T, E: Error + Send + 'static> WithContext<T, E> for Result<T, E>

Source§

fn with_err_context(self, context: impl ToString) -> Result<T, ErrorMessage>

Source§

fn with_dyn_err_context( self, context: impl FnOnce() -> String, ) -> Result<T, ErrorMessage>

Implementors§