1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
use std::fmt::Debug;
use crate::LoggableError;

/// Generic implementation for all errors that are [`Debug`](std::fmt::Debug).
impl<T, E: Debug> LoggableError<T> for std::result::Result<T, E> {
    fn print_error<F: Fn(&str)>(self, fun: F) -> Self {
        if let Err(ref err) = self {
            let msg = format!("ERROR: {err:#?}");
            fun(&msg);
        }
        self
    }
}

#[cfg(test)]
mod tests {
    use crate::LoggableError;
    use std::io;

    #[test]
    fn generic_std_result_is_error() {
        let res: Result<(), io::Error> = Err(io::Error::new(io::ErrorKind::NotFound, "Test"));

        assert!(res.to_stdout().is_err());
    }

    #[test]
    fn generic_std_result_error_keeps_type() {
        let res: Result<(), io::Error> = Err(io::Error::new(io::ErrorKind::NotFound, "Test"));

        assert!(<dyn std::any::Any>::is::<Result<(), io::Error>>(&res.to_stdout()));
    }
}