error-path 0.1.0

Attach stable, structured error paths to Result-based Rust errors with lightweight adapters.
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
420
421
422
423
424
425
426
427
428
429
430
431
//! `error-path` adds stable, structured operational addresses to Rust errors.
//!
//! The crate is intentionally tiny:
//! - [`WithErrorPath`] is the compatibility trait used by macros.
//! - [`ErrorPath`] is a structured operational address.
//! - Optional features adapt `anyhow`, `eyre`, `error-stack`, and `stacked_errors`.
//!
//! # Example
//!
//! ```rust
//! use error_path::ErrorPath;
//!
//! let mut error_path = ErrorPath::from_segment("http.0405");
//! error_path.prepend_path("login.api.request_login");
//!
//! assert_eq!(error_path.to_string(), "login.api.request_login.http.0405");
//! ```

use std::error::Error;
use std::fmt;
use std::sync::OnceLock;

#[cfg(any(feature = "anyhow", feature = "eyre"))]
use std::sync::Mutex;

#[cfg(feature = "macros")]
pub use error_path_macros::{error_path, error_path_impl, error_path_skip};

static PATH_DELIMITER: OnceLock<String> = OnceLock::new();

/// Error returned when the process-wide path delimiter cannot be configured.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SetPathDelimiterError {
    /// An empty delimiter was provided.
    Empty,
    /// The delimiter was already configured.
    AlreadySet,
}

impl fmt::Display for SetPathDelimiterError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => f.write_str("path delimiter must not be empty"),
            Self::AlreadySet => f.write_str("path delimiter is already set"),
        }
    }
}

impl Error for SetPathDelimiterError {}

/// Set the process-wide delimiter used by [`ErrorPath`] `Display`.
///
/// The delimiter can be set only once. Call this near application startup,
/// before errors are formatted. Reading or formatting a path before this call
/// initializes the delimiter to `"."`.
pub fn set_path_delimiter(delimiter: impl Into<String>) -> Result<(), SetPathDelimiterError> {
    let delimiter = delimiter.into();
    if delimiter.is_empty() {
        return Err(SetPathDelimiterError::Empty);
    }

    PATH_DELIMITER
        .set(delimiter)
        .map_err(|_| SetPathDelimiterError::AlreadySet)
}

/// Return the process-wide path delimiter.
///
/// The first call initializes an unset delimiter to `"."`.
pub fn path_delimiter() -> &'static str {
    PATH_DELIMITER.get_or_init(|| ".".to_owned()).as_str()
}

/// Compatibility trait used by the generated macro code.
///
/// Implement this trait for any error type that wants to work with
/// `#[error_path]` or `#[error_path_impl]`.
pub trait WithErrorPath: Sized {
    /// Return the same error value enriched with `path`.
    fn with_error_path(self, path: &'static str) -> Self;
}

/// Read a structured operational address from an error.
///
/// Implement this trait for an application error type that stores an
/// [`ErrorPath`]. Optional adapters implement it to expose only segments added
/// by [`WithErrorPath`]; they never infer a path or error code from a message.
/// The default implementation returns `None` when no structured address exists.
pub trait ErrorPathExt {
    /// Return this error's structured operational address, when available.
    fn error_path(&self) -> Option<ErrorPath> {
        None
    }
}

/// A structured operational error address.
///
/// Segments are kept separately so callers can use them in logs, JSON, or
/// storage without parsing a rendered string.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ErrorPath {
    segments: Vec<&'static str>,
}

impl ErrorPath {
    /// Create an empty error path.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a path from segments separated by [`path_delimiter`], ignoring
    /// empty segments.
    pub fn from_path(path: &'static str) -> Self {
        Self {
            segments: path
                .split(path_delimiter())
                .filter(|segment| !segment.is_empty())
                .collect(),
        }
    }

    /// Create a path using the configured delimiter.
    ///
    /// Prefer [`ErrorPath::from_path`]. This compatibility alias no longer
    /// assumes a dot delimiter.
    pub fn from_dot_separated(path: &'static str) -> Self {
        Self::from_path(path)
    }

    /// Create a path containing one atomic segment.
    ///
    /// Dots in `segment` are preserved. This is useful for a stable error code
    /// such as `http.0405`.
    pub fn from_segment(segment: &'static str) -> Self {
        let mut path = Self::new();
        path.push(segment);
        path
    }

    /// Path segments in outermost-to-innermost order.
    pub fn segments(&self) -> &[&'static str] {
        &self.segments
    }

    /// Render this path with `delimiter` between segments.
    pub fn to_string_with(&self, delimiter: &str) -> String {
        self.segments.join(delimiter)
    }

    /// Prepend segments separated by [`path_delimiter`], ignoring empty
    /// segments.
    pub fn prepend_path(&mut self, path: &'static str) {
        let prefix = Self::from_path(path);
        self.segments.splice(0..0, prefix.segments);
    }

    /// Prepend segments using the configured delimiter.
    ///
    /// Prefer [`ErrorPath::prepend_path`]. This compatibility alias no longer
    /// assumes a dot delimiter.
    pub fn prepend_dot_separated(&mut self, path: &'static str) {
        self.prepend_path(path);
    }

    /// Prepend one atomic segment.
    ///
    /// Dots in `segment` are preserved.
    pub fn prepend(&mut self, segment: &'static str) {
        if !segment.is_empty() {
            self.segments.insert(0, segment);
        }
    }

    /// Append one atomic segment.
    ///
    /// Dots in `segment` are preserved.
    pub fn push(&mut self, segment: &'static str) {
        if !segment.is_empty() {
            self.segments.push(segment);
        }
    }
}

impl fmt::Display for ErrorPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_string_with(path_delimiter()))
    }
}

/// Internal typed context used by adapters that expose downcasting.
///
/// The marker holds only segments added through [`WithErrorPath`]. It never
/// attempts to interpret an adapter's root error or text as an error code.
#[cfg(any(feature = "anyhow", feature = "eyre"))]
#[derive(Debug)]
struct AdapterErrorPath(Mutex<ErrorPath>);

#[cfg(any(feature = "anyhow", feature = "eyre"))]
impl AdapterErrorPath {
    fn new(path: &'static str) -> Self {
        Self(Mutex::new(ErrorPath::from_path(path)))
    }

    fn prepend(&self, path: &'static str) {
        self.0
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .prepend_path(path);
    }

    fn path(&self) -> ErrorPath {
        self.0
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .clone()
    }
}

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

#[cfg(feature = "anyhow")]
impl WithErrorPath for anyhow::Error {
    fn with_error_path(self, path: &'static str) -> Self {
        if let Some(error_path) = self.downcast_ref::<AdapterErrorPath>() {
            error_path.prepend(path);
            self
        } else {
            self.context(AdapterErrorPath::new(path))
        }
    }
}

#[cfg(feature = "anyhow")]
impl ErrorPathExt for anyhow::Error {
    fn error_path(&self) -> Option<ErrorPath> {
        self.downcast_ref::<AdapterErrorPath>()
            .map(AdapterErrorPath::path)
    }
}

#[cfg(feature = "eyre")]
impl WithErrorPath for eyre::Report {
    fn with_error_path(self, path: &'static str) -> Self {
        if let Some(error_path) = self.downcast_ref::<AdapterErrorPath>() {
            error_path.prepend(path);
            self
        } else {
            self.wrap_err(AdapterErrorPath::new(path))
        }
    }
}

#[cfg(feature = "eyre")]
impl ErrorPathExt for eyre::Report {
    fn error_path(&self) -> Option<ErrorPath> {
        self.downcast_ref::<AdapterErrorPath>()
            .map(AdapterErrorPath::path)
    }
}

/// Typed attachment used by the `error-stack` adapter.
#[cfg(feature = "error-stack")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ErrorPathSegment(pub &'static str);

#[cfg(feature = "error-stack")]
impl<C> WithErrorPath for error_stack::Report<C> {
    fn with_error_path(self, path: &'static str) -> Self {
        self.attach(ErrorPathSegment(path))
    }
}

#[cfg(feature = "error-stack")]
impl<C> ErrorPathExt for error_stack::Report<C> {
    fn error_path(&self) -> Option<ErrorPath> {
        let segments: Vec<_> = self
            .frames()
            .filter_map(|frame| frame.downcast_ref::<ErrorPathSegment>())
            .flat_map(|segment| {
                segment
                    .0
                    .split(path_delimiter())
                    .filter(|part| !part.is_empty())
            })
            .collect();

        (!segments.is_empty()).then_some(ErrorPath { segments })
    }
}

/// Internal typed error stored in `stacked_errors` frames.
#[cfg(feature = "stacked-errors")]
#[derive(Debug)]
struct StackedErrorPathSegment(&'static str);

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

#[cfg(feature = "stacked-errors")]
impl Error for StackedErrorPathSegment {}

#[cfg(feature = "stacked-errors")]
impl WithErrorPath for stacked_errors::Error {
    fn with_error_path(self, path: &'static str) -> Self {
        self.add_kind_locationless(stacked_errors::ErrorKind::from_err(
            StackedErrorPathSegment(path),
        ))
    }
}

#[cfg(feature = "stacked-errors")]
impl ErrorPathExt for stacked_errors::Error {
    fn error_path(&self) -> Option<ErrorPath> {
        let segments: Vec<_> = self
            .stack
            .iter()
            .rev()
            .filter_map(|(kind, _)| match kind {
                stacked_errors::ErrorKind::BoxedError(error) => {
                    error.downcast_ref::<StackedErrorPathSegment>()
                }
                _ => None,
            })
            .flat_map(|segment| {
                segment
                    .0
                    .split(path_delimiter())
                    .filter(|part| !part.is_empty())
            })
            .collect();

        (!segments.is_empty()).then_some(ErrorPath { segments })
    }
}

#[cfg(all(
    test,
    any(feature = "anyhow", feature = "eyre", feature = "stacked-errors")
))]
mod tests {
    use super::*;

    #[cfg(feature = "anyhow")]
    #[test]
    fn anyhow_adapter_adds_path_context() {
        let err = anyhow::anyhow!("root").with_error_path("service.load");

        assert_eq!(err.to_string(), "service.load");
    }

    #[cfg(feature = "anyhow")]
    #[test]
    fn anyhow_adapter_exposes_only_macro_path() {
        let err = anyhow::anyhow!("HTTP communication failed")
            .with_error_path("request_login")
            .with_error_path("login.api");

        assert_eq!(
            err.error_path().unwrap().to_string(),
            "login.api.request_login"
        );
    }

    #[cfg(feature = "eyre")]
    #[test]
    fn eyre_adapter_adds_path_context() {
        let err = eyre::eyre!("root").with_error_path("service.load");

        assert_eq!(err.to_string(), "service.load");
    }

    #[cfg(feature = "eyre")]
    #[test]
    fn eyre_adapter_exposes_only_macro_path() {
        let err = eyre::eyre!("HTTP communication failed")
            .with_error_path("request_login")
            .with_error_path("login.api");

        assert_eq!(
            err.error_path().unwrap().to_string(),
            "login.api.request_login"
        );
    }

    #[cfg(feature = "error-stack")]
    #[test]
    fn error_stack_adapter_exposes_only_macro_path() {
        let err = error_stack::Report::new(std::io::Error::other("HTTP communication failed"))
            .with_error_path("request_login")
            .with_error_path("login.api");

        assert_eq!(
            err.error_path().unwrap().to_string(),
            "login.api.request_login"
        );
    }

    #[cfg(feature = "stacked-errors")]
    #[test]
    fn stacked_errors_adapter_adds_path_context() {
        let err =
            stacked_errors::Error::from_kind_locationless("root").with_error_path("service.load");

        let rendered = err.to_string();
        assert!(rendered.contains("root"));
        assert!(rendered.contains("service.load"));
    }

    #[cfg(feature = "stacked-errors")]
    #[test]
    fn stacked_errors_adapter_exposes_only_macro_path() {
        let err = stacked_errors::Error::from_kind_locationless("HTTP communication failed")
            .with_error_path("request_login")
            .with_error_path("login.api");

        assert_eq!(
            err.error_path().unwrap().to_string(),
            "login.api.request_login"
        );
    }
}