n0_error/
any.rs

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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use std::{
    convert::Infallible,
    fmt::{self, Formatter},
    ops::Deref,
};

use crate::{ErrorRef, FromString, Meta, SourceFormat, StackError, StackErrorExt};

/// Type-erased error that can wrap a [`StackError`] or any [`std::error::Error`].
///
/// [`StackError`]s have a blanket impl to convert into [`AnyError`], while preserving
/// their call-site location info.
///
/// Errors that implement [`std::error::Error`] but not [`StackError`] can't convert to
/// [`AnyError`] automatically. Use either [`AnyError::from_std`] or [`crate::StdResultExt::e`]
/// to convert std errors into [`AnyError`].
///
/// This is necessary unfortunately because if we had a blanket conversion from std errors to `AnyError`,
/// this blanket conversion would also apply to [`StackError`]s, thus losing their call-site location
/// info in the conversion.
pub struct AnyError(Inner);

enum Inner {
    Stack(Box<dyn StackError>),
    Std(Box<dyn std::error::Error + Send + Sync>, Meta),
}

impl AnyError {
    /// Creates an [`AnyError`] from a std error.
    ///
    /// This captures call-site metadata.
    #[track_caller]
    pub fn from_std(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self::from_std_box(Box::new(err))
    }

    /// Creates an [`AnyError`] from a [`anyhow::Error`].
    #[track_caller]
    #[cfg(feature = "anyhow")]
    pub fn from_anyhow(err: anyhow::Error) -> Self {
        Self::from_std_box(err.into_boxed_dyn_error())
    }

    /// Creates an [`AnyError`] from a bosed std error.
    ///
    /// This captures call-site metadata.
    #[track_caller]
    pub fn from_std_box(err: Box<dyn std::error::Error + Send + Sync + 'static>) -> Self {
        Self(Inner::Std(err, Meta::default()))
    }

    /// Creates an [`AnyError`] from any `Display` value by formatting it into a message.
    #[track_caller]
    pub fn from_display(s: impl fmt::Display) -> Self {
        Self::from_string(s.to_string())
    }

    /// Creates an [`AnyError`] from a message string.
    #[track_caller]
    pub fn from_string(message: String) -> Self {
        FromString::WithoutSource {
            message,
            meta: Meta::default(),
        }
        .into_any()
    }

    /// Creates an [`AnyError`] from a [`StackError`].
    ///
    /// This preserves the error's call-site metadata.
    ///
    /// Equivalent to `AnyError::from(err)`.
    #[track_caller]
    pub fn from_stack(err: impl StackError + 'static) -> Self {
        Self::from_stack_box(Box::new(err))
    }

    /// Creates an [`AnyError`] from a boxed [`StackError`].
    #[track_caller]
    pub fn from_stack_box(err: Box<dyn StackError>) -> Self {
        Self(Inner::Stack(err))
    }

    /// Adds additional context on top of this error.
    #[track_caller]
    pub fn context(self, context: impl fmt::Display) -> AnyError {
        FromString::WithSource {
            message: context.to_string(),
            source: self,
            meta: Meta::default(),
        }
        .into_any()
    }

    /// Converts into boxed std error.
    pub fn into_boxed_dyn_error(self) -> Box<dyn std::error::Error + Send + Sync + 'static> {
        Box::new(self)
    }
}

impl fmt::Display for AnyError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_ref())?;
        if f.alternate() {
            self.report().fmt_sources(f, SourceFormat::OneLine)?;
        }
        Ok(())
    }
}

impl fmt::Debug for AnyError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            match &self.0 {
                Inner::Stack(error) => {
                    write!(f, "Stack({error:#?})")
                }
                Inner::Std(error, meta) => {
                    write!(f, "Std({error:#?}, {meta:?})")
                }
            }
        } else {
            self.report().full().format(f)
        }
    }
}

impl StackError for AnyError {
    fn as_dyn(&self) -> &dyn StackError {
        self
    }

    fn as_std(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
        match &self.0 {
            Inner::Std(err, _) => err.as_ref(),
            Inner::Stack(err) => err.as_std(),
        }
    }

    fn meta(&self) -> Option<&Meta> {
        match &self.0 {
            Inner::Std(_, meta) => Some(meta),
            Inner::Stack(err) => err.meta(),
        }
    }

    fn source(&self) -> Option<ErrorRef<'_>> {
        self.as_ref().source()
    }

    fn is_transparent(&self) -> bool {
        self.as_ref().is_transparent()
    }

    fn as_ref<'a>(&'a self) -> ErrorRef<'a> {
        match &self.0 {
            Inner::Stack(error) => ErrorRef::Stack(error.deref()),
            Inner::Std(error, meta) => ErrorRef::std_with_meta(error.as_ref(), meta),
        }
    }
}

impl std::error::Error for AnyError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.as_std().source()
    }
}

impl From<String> for AnyError {
    #[track_caller]
    fn from(value: String) -> Self {
        Self::from_display(value)
    }
}

impl From<&str> for AnyError {
    #[track_caller]
    fn from(value: &str) -> Self {
        Self::from_display(value)
    }
}

impl From<Box<dyn std::error::Error + Send + Sync>> for AnyError {
    #[track_caller]
    fn from(value: Box<dyn std::error::Error + Send + Sync>) -> Self {
        Self::from_std_box(value)
    }
}

#[cfg(feature = "anyhow")]
impl From<anyhow::Error> for AnyError {
    #[track_caller]
    fn from(value: anyhow::Error) -> Self {
        Self::from_anyhow(value)
    }
}

impl std::str::FromStr for AnyError {
    type Err = Infallible;

    #[track_caller]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self::from_display(s))
    }
}