Skip to main content

error_ext/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3//! Error utilities.
4
5#![warn(missing_docs)]
6
7#[cfg(feature = "axum")]
8#[cfg_attr(docsrs, doc(cfg(feature = "axum")))]
9pub mod axum;
10
11use std::error::Error as StdError;
12
13/// Convenience for `async` and `anyhow` friendly dynamic error
14/// `Box<dyn std::error::Error + Send + Sync + 'static>`.
15pub type BoxError = Box<dyn StdError + Send + Sync + 'static>;
16
17/// Extension methods for std errors.
18pub trait StdErrorExt
19where
20    Self: StdError,
21{
22    /// Format this error as a chain of colon separated strings built from this error and all
23    /// recursive sources.
24    ///
25    /// Can be used to log errors like this:
26    ///
27    /// `error!(error = error.as_chain(), "cannot do this or that");`
28    fn as_chain(&self) -> String {
29        let mut sources = vec![];
30        sources.push(self.to_string());
31
32        let mut source = self.source();
33        while let Some(s) = source {
34            sources.push(s.to_string());
35            source = s.source();
36        }
37
38        sources.join(": ")
39    }
40
41    /// Converts this error – given it implements `Sized` + `Send` +`Sync` and `'static` – into a
42    /// [BoxError].
43    fn into_boxed(self) -> BoxError
44    where
45        Self: Sized + Send + Sync + 'static,
46    {
47        self.into()
48    }
49}
50
51impl<T> StdErrorExt for T where T: StdError {}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56    use thiserror::Error;
57
58    #[derive(Debug, Error)]
59    #[error("outer")]
60    struct Outer(#[source] Inner);
61
62    #[derive(Debug, Error)]
63    #[error("inner")]
64    struct Inner;
65
66    #[test]
67    fn test_as_chain() {
68        let error = Outer(Inner);
69        assert_eq!(error.as_chain(), "outer: inner");
70    }
71
72    #[test]
73    fn test_into_boxed() {
74        let error = Outer(Inner);
75        let error = error.into_boxed();
76        assert_eq!(error.to_string(), "outer");
77    }
78}