forked from torrust/torrust-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocated_error.rs
More file actions
103 lines (88 loc) · 2.22 KB
/
located_error.rs
File metadata and controls
103 lines (88 loc) · 2.22 KB
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,
{
source: Arc<E>,
location: Box<Location<'a>>,
}
impl<'a, E> std::fmt::Display for LocatedError<'a, E>
where
E: Error + ?Sized,
{
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 + 'static,
{
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&self.source)
}
}
impl<'a, E> Clone for LocatedError<'a, E>
where
E: Error + ?Sized,
{
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,
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>> for Arc<dyn std::error::Error> {
#[track_caller]
fn into(self) -> LocatedError<'a, dyn std::error::Error> {
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());
}
}