ts_error/
logger.rs

1use core::{fmt, panic::Location};
2
3/// Trait to log an error.
4pub trait LogError {
5    /// Log the error.
6    #[track_caller]
7    fn log_err(self) -> Self;
8}
9
10#[cfg(feature = "std")]
11/// Trait to log an error to `stderr`.
12pub trait StderrError {
13    /// Display the error in `stderr`.
14    #[track_caller]
15    fn stderr_err(self) -> Self;
16}
17
18impl<T, E: fmt::Display> LogError for Result<T, E> {
19    #[track_caller]
20    fn log_err(self) -> Self {
21        if let Err(error) = self.as_ref() {
22            let location = Location::caller();
23            log::error!("[{location}] {error}");
24        }
25        self
26    }
27}
28
29#[cfg(feature = "std")]
30impl<T, E: fmt::Display> StderrError for Result<T, E> {
31    #[track_caller]
32    fn stderr_err(self) -> Self {
33        if let Err(error) = self.as_ref() {
34            let location = Location::caller();
35            std::eprintln!("{}", ts_ansi::format_error!("[{location}] {error}"));
36        }
37        self
38    }
39}
40
41impl<T> LogError for Option<T> {
42    #[track_caller]
43    fn log_err(self) -> Self {
44        if self.is_none() {
45            let location = Location::caller();
46            log::error!("[{location}] value was None");
47        }
48        self
49    }
50}
51
52#[cfg(feature = "std")]
53impl<T> StderrError for Option<T> {
54    #[track_caller]
55    fn stderr_err(self) -> Self {
56        if self.is_none() {
57            let location = Location::caller();
58            std::eprintln!("{}", ts_ansi::format_error!("[{location}] value was None"));
59        }
60        self
61    }
62}