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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
//! This crate provides a wrapper around an error that includes the location of
//! the error.
//!
//! ```rust
//! use std::error::Error;
//! use std::panic::Location;
//! use std::sync::Arc;
//! use torrust_tracker_located_error::{Located, LocatedError};
//!
//! #[derive(thiserror::Error, Debug)]
//! enum TestError {
//!     #[error("Test")]
//!     Test,
//! }
//!
//! #[track_caller]
//! fn get_caller_location() -> Location<'static> {
//!     *Location::caller()
//! }
//!
//! let e = TestError::Test;
//!
//! let b: LocatedError<TestError> = Located(e).into();
//! let l = get_caller_location();
//!
//! assert!(b.to_string().contains("Test, src/lib.rs"));
//! ```
//!
//! # Credits
//!
//! <https://stackoverflow.com/questions/74336993/getting-line-numbers-with-when-using-boxdyn-stderrorerror>
use std::error::Error;
use std::panic::Location;
use std::sync::Arc;

/// A generic wrapper around an error.
///
/// Where `E` is the inner error (source error).
pub struct Located<E>(pub E);

/// A wrapper around an error that includes the location of the error.
#[derive(Debug)]
pub struct LocatedError<'a, E>
where
    E: Error + ?Sized + Send + Sync,
{
    source: Arc<E>,
    location: Box<Location<'a>>,
}

impl<'a, E> std::fmt::Display for LocatedError<'a, E>
where
    E: Error + ?Sized + Send + Sync,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}, {}", self.source, self.location)
    }
}

impl<'a, E> Error for LocatedError<'a, E>
where
    E: Error + ?Sized + Send + Sync + 'static,
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.source)
    }
}

impl<'a, E> Clone for LocatedError<'a, E>
where
    E: Error + ?Sized + Send + Sync,
{
    fn clone(&self) -> Self {
        LocatedError {
            source: self.source.clone(),
            location: self.location.clone(),
        }
    }
}

#[allow(clippy::from_over_into)]
impl<'a, E> Into<LocatedError<'a, E>> for Located<E>
where
    E: Error + Send + Sync,
    Arc<E>: Clone,
{
    #[track_caller]
    fn into(self) -> LocatedError<'a, E> {
        let e = LocatedError {
            source: Arc::new(self.0),
            location: Box::new(*std::panic::Location::caller()),
        };
        log::debug!("{e}");
        e
    }
}

#[allow(clippy::from_over_into)]
impl<'a> Into<LocatedError<'a, dyn std::error::Error + Send + Sync>> for Arc<dyn std::error::Error + Send + Sync> {
    #[track_caller]
    fn into(self) -> LocatedError<'a, dyn std::error::Error + Send + Sync> {
        LocatedError {
            source: self,
            location: Box::new(*std::panic::Location::caller()),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::panic::Location;

    use super::LocatedError;
    use crate::Located;

    #[derive(thiserror::Error, Debug)]
    enum TestError {
        #[error("Test")]
        Test,
    }

    #[track_caller]
    fn get_caller_location() -> Location<'static> {
        *Location::caller()
    }

    #[test]
    fn error_should_include_location() {
        let e = TestError::Test;

        let b: LocatedError<'_, TestError> = Located(e).into();
        let l = get_caller_location();

        assert_eq!(b.location.file(), l.file());
    }
}