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
// 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;

pub struct Located<E>(pub E);

#[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_error::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());
    }
}