ts_error/
logger.rs

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