Trait ErrorTrace

Source
pub trait ErrorTrace: Error {
    // Required methods
    fn freeze(&self) -> Trace;
    fn trace(&self) -> ErrorTraceFormatter<'_, '_, '_>;
}
Expand description

Allows one to write an error and all of its dependencies.

§Example

use std::error::Error;
use std::fmt::{Display, Formatter, Result as FResult};

use error_trace::ErrorTrace as _;

#[derive(Debug)]
struct SomeError {
    msg: String,
}
impl Display for SomeError {
    fn fmt(&self, f: &mut Formatter<'_>) -> FResult { write!(f, "{}", self.msg) }
}
impl Error for SomeError {}

#[derive(Debug)]
struct HigherError {
    msg:   String,
    child: SomeError,
}
impl Display for HigherError {
    fn fmt(&self, f: &mut Formatter<'_>) -> FResult { write!(f, "{}", self.msg) }
}
impl Error for HigherError {
    fn source(&self) -> Option<&(dyn 'static + Error)> { Some(&self.child) }
}



let err = HigherError {
    msg:   "Oh no, something went wrong!".into(),
    child: SomeError { msg: "A specific reason".into() },
};
assert_eq!(
    err.trace().to_string(),
    r#"Oh no, something went wrong!

Caused by:
 o A specific reason

"#
);

Required Methods§

Source

fn freeze(&self) -> Trace

“Freezes” the trace of this error.

This is useful in case you’re dealing with errors where you don’t want to propagate the type (e.g., due to lifetimes) but do want to propagate the trace.

§Returns

A Trace that returns the same trace when formatter, except all errors are serialized to Strings.

§Example
use error_trace::ErrorTrace as _;

let err = HigherError {
    msg:   "Oh no, something went wrong!".into(),
    child: SomeError { msg: "A specific reason".into() },
};
assert_eq!(
    err.freeze().trace().to_string(),
    r#"Oh no, something went wrong!

Caused by:
 o A specific reason

"#
);
Source

fn trace(&self) -> ErrorTraceFormatter<'_, '_, '_>

Returns a formatter for showing this Error and all its sources.

This function can be used similarly to Path::display(), since its result implements both Debug and Display.

§Returns

A new ErrorTraceFormatter that implements Debug and Display.

§Example
use error_trace::ErrorTrace as _;

let err = HigherError { msg: "Oh no, something went wrong!".into(), child: SomeError { msg: "A specific reason".into() } };
assert_eq!(err.trace().to_string(), r#"Oh no, something went wrong!

Caused by:
 o A specific reason

"#);

Implementors§

Source§

impl<T: ?Sized + Error> ErrorTrace for T