orion-error 0.8.0

Struct Error for Large Project
Documentation
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use std::{error::Error as StdError, fmt};

use crate::{core::DomainReason, StructError};

mod private {
    pub trait Sealed {}
}

/// Marker trait for explicitly opt-in raw `std::error::Error` sources.
///
/// This is the explicit escape hatch for downstream crates that have their own raw
/// `StdError` types and want to route them through `raw_source(...)` before
/// calling `source_err(...)`.
///
/// # Example
///
/// ```rust
/// use orion_error::interop::{raw_source, RawStdError};
/// use orion_error::prelude::*;
/// use orion_error::UnifiedReason;
///
/// #[derive(Debug)]
/// struct MyError;
///
/// impl std::fmt::Display for MyError {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
///         write!(f, "my error")
///     }
/// }
///
/// impl std::error::Error for MyError {}
/// impl RawStdError for MyError {}
///
/// let result: Result<(), MyError> = Err(MyError);
/// let err = result
///     .map_err(raw_source)
///     .source_err(UnifiedReason::system_error(), "my operation failed")
///     .unwrap_err();
///
/// assert_eq!(err.source_ref().unwrap().to_string(), "my error");
/// ```
///
/// Implement this trait only for genuine non-structured raw error types.
/// Do not implement it for wrappers around `StructError<_>`.
pub trait RawStdError: StdError + Send + Sync + 'static {}

#[doc(hidden)]
pub trait UnstructuredSource: private::Sealed {
    fn into_struct_error<R>(self, reason: R, detail: String) -> StructError<R>
    where
        R: DomainReason;
}

/// Convert a `Result<T, E>` into `Result<T, StructError<R>>`, attaching the
/// original error as the source of the new structured error.
///
/// Works for both raw `std::error::Error` types and already-structured
/// `StructError` sources.
///
/// # Example
///
/// ```rust
/// use orion_error::prelude::*;
/// use orion_error::UnifiedReason;
///
/// let result: Result<(), std::io::Error> = Err(std::io::Error::other("disk offline"));
/// let err: Result<(), StructError<UnifiedReason>> =
///     result.source_err(UnifiedReason::system_error(), "read config");
/// assert!(err.unwrap_err().detail().as_deref() == Some("read config"));
/// ```
///
/// # Note on trait resolution
///
/// There are two blanket impls: one for raw `StdError` sources (via
/// `UnstructuredSource`), and one for already-structured `StructError`
/// sources. These do not conflict because `StructError<R>` does not
/// implement `UnstructuredSource`.
pub trait SourceErr<T, R: DomainReason>: Sized {
    fn source_err(self, reason: R, detail: impl Into<String>) -> Result<T, StructError<R>>;
}

#[derive(Debug)]
pub struct RawSource<E>(E);

/// Explicitly mark an opt-in raw `std::error::Error` as an unstructured source.
///
/// This is a narrow explicit escape hatch. It does **not** provide a blanket
/// `E: StdError` path, and it must not be used for `StructError<_>`.
///
/// Downstream crates may opt in their own raw `StdError` types by implementing
/// [`RawStdError`], instead of relying on a blanket `E: StdError` fallback.
///
/// ```rust
/// use std::fmt;
///
/// use orion_error::prelude::*;
/// use orion_error::UnifiedReason;
/// use orion_error::interop::{raw_source, RawStdError};
///
/// #[derive(Debug)]
/// struct ThirdPartyError;
///
/// impl fmt::Display for ThirdPartyError {
///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
///         write!(f, "third-party failure")
///     }
/// }
///
/// impl std::error::Error for ThirdPartyError {}
/// impl RawStdError for ThirdPartyError {}
///
/// let result: Result<(), ThirdPartyError> = Err(ThirdPartyError);
/// let err = result
///     .map_err(raw_source)
///     .source_err(UnifiedReason::system_error(), "load failed")
///     .expect_err("expected structured error");
///
/// assert_eq!(err.source_ref().unwrap().to_string(), "third-party failure");
/// ```
///
/// ```compile_fail
/// use orion_error::{StructError, UnifiedReason};
/// use orion_error::interop::{raw_source, RawStdError};
///
/// let structured = StructError::from(UnifiedReason::system_error());
/// let _ = raw_source(structured);
/// ```
pub fn raw_source<E>(err: E) -> RawSource<E>
where
    E: RawStdError,
{
    RawSource(err)
}

impl<E> RawSource<E> {
    pub fn into_inner(self) -> E {
        self.0
    }

    pub fn inner(&self) -> &E {
        &self.0
    }
}

impl<E: fmt::Display> fmt::Display for RawSource<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl<E> StdError for RawSource<E>
where
    E: RawStdError,
{
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        Some(&self.0)
    }
}

impl<T, E, R> SourceErr<T, R> for Result<T, E>
where
    E: UnstructuredSource,
    R: DomainReason,
{
    fn source_err(self, reason: R, detail: impl Into<String>) -> Result<T, StructError<R>> {
        let detail = detail.into();
        self.map_err(|err| err.into_struct_error(reason, detail))
    }
}

fn attach_std_source<E, R>(err: E, reason: R, detail: String) -> StructError<R>
where
    E: StdError + Send + Sync + 'static,
    R: DomainReason,
{
    StructError::from(reason)
        .with_detail(detail)
        .with_std_source(err)
}

impl RawStdError for std::io::Error {}

impl private::Sealed for std::io::Error {}

impl UnstructuredSource for std::io::Error {
    fn into_struct_error<R>(self, reason: R, detail: String) -> StructError<R>
    where
        R: DomainReason,
    {
        attach_std_source(self, reason, detail)
    }
}

impl<E> private::Sealed for RawSource<E> where E: RawStdError {}

impl<E> UnstructuredSource for RawSource<E>
where
    E: RawStdError,
{
    fn into_struct_error<R>(self, reason: R, detail: String) -> StructError<R>
    where
        R: DomainReason,
    {
        attach_std_source(self.0, reason, detail)
    }
}

#[cfg(feature = "anyhow")]
#[derive(Debug)]
struct AnyhowStdSource(anyhow::Error);

#[cfg(feature = "anyhow")]
impl fmt::Display for AnyhowStdSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[cfg(feature = "anyhow")]
impl StdError for AnyhowStdSource {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        self.0.source()
    }
}

#[cfg(feature = "anyhow")]
impl private::Sealed for anyhow::Error {}

#[cfg(feature = "anyhow")]
impl UnstructuredSource for anyhow::Error {
    fn into_struct_error<R>(self, reason: R, detail: String) -> StructError<R>
    where
        R: DomainReason,
    {
        use crate::core::OwnedDynStdStructError;

        match self.downcast::<OwnedDynStdStructError>() {
            Ok(source) => StructError::from(reason)
                .with_detail(detail)
                .with_dyn_struct_source(source),
            Err(err) => attach_std_source(AnyhowStdSource(err), reason, detail),
        }
    }
}

// Requires feature: "serde_json"
#[cfg(feature = "serde_json")]
impl RawStdError for serde_json::Error {}

// Requires feature: "serde_json"
#[cfg(feature = "serde_json")]
impl private::Sealed for serde_json::Error {}

// Requires feature: "serde_json"
#[cfg(feature = "serde_json")]
impl UnstructuredSource for serde_json::Error {
    fn into_struct_error<R>(self, reason: R, detail: String) -> StructError<R>
    where
        R: DomainReason,
    {
        attach_std_source(self, reason, detail)
    }
}

#[cfg(feature = "toml")]
impl RawStdError for toml::de::Error {}

#[cfg(feature = "toml")]
impl private::Sealed for toml::de::Error {}

#[cfg(feature = "toml")]
impl UnstructuredSource for toml::de::Error {
    fn into_struct_error<R>(self, reason: R, detail: String) -> StructError<R>
    where
        R: DomainReason,
    {
        attach_std_source(self, reason, detail)
    }
}

#[cfg(feature = "toml")]
impl RawStdError for toml::ser::Error {}

#[cfg(feature = "toml")]
impl private::Sealed for toml::ser::Error {}

#[cfg(feature = "toml")]
impl UnstructuredSource for toml::ser::Error {
    fn into_struct_error<R>(self, reason: R, detail: String) -> StructError<R>
    where
        R: DomainReason,
    {
        attach_std_source(self, reason, detail)
    }
}

// Allow `source_err` to work with already-structured `Result<T, StructError<R1>>`
// sources. Callers no longer need to distinguish between raw std errors and
// structured errors — `source_err` handles both.
impl<T, R1, R2> SourceErr<T, R2> for Result<T, StructError<R1>>
where
    R1: DomainReason,
    R2: DomainReason,
{
    fn source_err(self, reason: R2, detail: impl Into<String>) -> Result<T, StructError<R2>> {
        let detail = detail.into();
        self.map_err(|err| {
            StructError::from(reason)
                .with_detail(detail)
                .with_struct_source(err)
        })
    }
}

#[cfg(test)]
mod tests {
    use std::{fmt, io};

    use super::{raw_source, RawStdError, SourceErr};
    use crate::StructError;
    use crate::UnifiedReason;

    #[derive(Debug)]
    struct ThirdPartyError(&'static str);

    impl fmt::Display for ThirdPartyError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{}", self.0)
        }
    }

    impl std::error::Error for ThirdPartyError {}

    impl RawStdError for ThirdPartyError {}

    #[test]
    fn test_source_err_for_io_error() {
        let result: Result<(), io::Error> = Err(io::Error::other("disk offline"));

        let err = result
            .source_err(UnifiedReason::system_error(), "load config failed")
            .expect_err("expected structured error");

        assert_eq!(err.detail().as_deref(), Some("load config failed"));
        assert_eq!(err.source_ref().unwrap().to_string(), "disk offline");
    }

    #[test]
    fn test_source_err_for_raw_source_wrapper() {
        let result: Result<(), ThirdPartyError> = Err(ThirdPartyError("parser aborted"));

        let err = result
            .map_err(raw_source)
            .source_err(UnifiedReason::validation_error(), "parse config failed")
            .expect_err("expected structured error");

        assert_eq!(err.detail().as_deref(), Some("parse config failed"));
        assert_eq!(err.source_ref().unwrap().to_string(), "parser aborted");
    }

    #[cfg(feature = "anyhow")]
    #[test]
    fn test_source_err_for_anyhow_defaults_to_unstructured_source() {
        let result: Result<(), anyhow::Error> = Err(anyhow::anyhow!("network offline"));

        let err = result
            .source_err(UnifiedReason::system_error(), "load config failed")
            .expect_err("expected structured error");

        assert_eq!(err.detail().as_deref(), Some("load config failed"));
        assert_eq!(err.source_ref().unwrap().to_string(), "network offline");
        assert_eq!(err.source_frames()[0].message, "network offline");
    }

    #[cfg(feature = "anyhow")]
    #[test]
    fn test_source_err_for_anyhow_extracts_top_level_official_dyn_bridge() {
        let structured = StructError::from(UnifiedReason::validation_error())
            .with_detail("invalid port")
            .with_std_source(io::Error::other("not a number"));
        let structured_display = structured.to_string();
        let result: Result<(), anyhow::Error> = Err(anyhow::Error::new(structured.into_dyn_std()));

        let err = result
            .source_err(UnifiedReason::system_error(), "load config failed")
            .expect_err("expected structured error");

        assert_eq!(err.detail().as_deref(), Some("load config failed"));
        assert_eq!(err.source_ref().unwrap().to_string(), structured_display);
        assert_eq!(err.source_frames()[0].message, "validation error");
        assert_eq!(
            err.source_frames()[0].reason.as_deref(),
            Some("validation error")
        );
        assert_eq!(
            err.source_frames()[0].detail.as_deref(),
            Some("invalid port")
        );
        assert_eq!(err.root_cause().unwrap().to_string(), "not a number");
    }

    #[test]
    fn test_source_err_for_struct_error_source() {
        // source_err works on Result<T, StructError<R1>> too (wraps as struct source)
        let inner: Result<(), StructError<UnifiedReason>> =
            Err(StructError::from(UnifiedReason::validation_error()).with_detail("inner detail"));

        let outer: Result<(), StructError<UnifiedReason>> =
            inner.source_err(UnifiedReason::system_error(), "outer wrapper");

        let err = outer.unwrap_err();
        assert_eq!(err.detail().as_deref(), Some("outer wrapper"));

        // The inner error becomes a structured source
        let frames = err.source_frames();
        assert_eq!(frames[0].message, "validation error");
        assert_eq!(frames[0].detail.as_deref(), Some("inner detail"));
    }
}