pub struct DisplayErrorChain<'a, E: ?Sized>(_);
Expand description

Provides an fmt::Display implementation for an error as a chain.

use display_error_chain::{DisplayErrorChain, ErrorChainExt as _};

// Let's set up a custom error. Normally one would use `snafu` or
// something similar to avoid the boilerplate.
#[derive(Debug)]
enum CustomError {
    NoCause,
    IO { source: std::io::Error },
}

// Custom display implementation (which doesn't take error
// sources into consideration).
impl std::fmt::Display for CustomError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CustomError::NoCause => {
                write!(f, "No cause")
            }
            CustomError::IO { .. } => {
                write!(f, "Some I/O")
            }
        }
    }
}

impl std::error::Error for CustomError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            CustomError::NoCause => None,
            CustomError::IO { source } => Some(source),
        }
    }
}

// And finally let's see how `DisplayErrorChain` helps!
let io = CustomError::IO {
    source: std::io::Error::new(std::io::ErrorKind::AlreadyExists, "wow"),
};
let formatted = DisplayErrorChain::new(&io).to_string();
assert_eq!("Some I/O\nCaused by:\n  -> wow", formatted);

let no_cause = CustomError::NoCause;
// You can also use a `.chain()` shortcut from the `ErrorChainExt` trait.
let formatted = no_cause.chain().to_string();
assert_eq!("No cause", formatted);

Implementations

Initializes the formatter with the error provided.

Trait Implementations

Formats the value using the given formatter. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Converts the given value to a String. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.