51 lines
1.1 KiB
Rust
51 lines
1.1 KiB
Rust
use std::{
|
|
error::Error,
|
|
fmt::{Debug, Display, Formatter},
|
|
};
|
|
|
|
#[derive(Debug)]
|
|
pub struct ErrorWithSuggestion<E, S> {
|
|
error: E,
|
|
suggestion: S,
|
|
}
|
|
|
|
impl<E: Display, S: Display> Display for ErrorWithSuggestion<E, S> {
|
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
|
self.error.fmt(f)?;
|
|
writeln!(f)?;
|
|
|
|
write!(f, "💡 ")?;
|
|
self.suggestion.fmt(f)?;
|
|
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
impl<E: Error, S: Debug + Display> Error for ErrorWithSuggestion<E, S> {
|
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
|
self.error.source()
|
|
}
|
|
}
|
|
|
|
pub trait ResultExt {
|
|
type O;
|
|
type E;
|
|
|
|
fn with_suggestion<Suggestion: Display>(
|
|
self,
|
|
suggestion: Suggestion,
|
|
) -> Result<Self::O, ErrorWithSuggestion<Self::E, Suggestion>>;
|
|
}
|
|
|
|
impl<Ok, Err> ResultExt for Result<Ok, Err> {
|
|
type O = Ok;
|
|
type E = Err;
|
|
|
|
fn with_suggestion<Suggestion: Display>(
|
|
self,
|
|
suggestion: Suggestion,
|
|
) -> Result<Self::O, ErrorWithSuggestion<Self::E, Suggestion>> {
|
|
self.map_err(|error| ErrorWithSuggestion { error, suggestion })
|
|
}
|
|
}
|