Skip to main content

domain_status/error_handling/
error_ext.rs

1//! Extension trait for formatting error chains (Mullvad-style).
2//!
3//! Provides a single, consistent string representation of an error and its causes
4//! for user-facing output.
5
6use std::error::Error;
7use std::fmt::Write;
8
9/// Extension trait for errors that formats the full error chain.
10///
11/// Use in `main` or CLI code to print a single, consistent "Error: ... Caused by: ..."
12/// message to stderr, then optionally call [`log_error_chain`](crate::error_handling::log_error_chain)
13/// to write the same chain to the log.
14pub trait ErrorExt {
15    /// Returns a string representation of the entire error chain.
16    fn display_chain(&self) -> String;
17
18    /// Like [`display_chain`](Self::display_chain) but with an extra message at the start.
19    fn display_chain_with_msg(&self, msg: &str) -> String;
20}
21
22impl<E: Error + ?Sized> ErrorExt for E {
23    fn display_chain(&self) -> String {
24        let mut s = format!("Error: {self}");
25        let mut source = self.source();
26        while let Some(err) = source {
27            let _ = write!(&mut s, "\nCaused by: {err}");
28            source = err.source();
29        }
30        s
31    }
32
33    fn display_chain_with_msg(&self, msg: &str) -> String {
34        let mut s = format!("Error: {msg}\nCaused by: {self}");
35        let mut source = self.source();
36        while let Some(err) = source {
37            let _ = write!(&mut s, "\nCaused by: {err}");
38            source = err.source();
39        }
40        s
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn display_chain_single_error() {
50        let e: anyhow::Error = anyhow::anyhow!("root");
51        let s = e.display_chain();
52        assert!(s.starts_with("Error: root"));
53        assert!(!s.contains("Caused by"));
54    }
55
56    #[test]
57    fn display_chain_with_cause() {
58        let e: anyhow::Error = anyhow::anyhow!("outer").context("inner");
59        let s = e.display_chain();
60        assert!(s.contains("Error:"));
61        assert!(s.contains("Caused by:"));
62    }
63
64    #[test]
65    fn display_chain_with_msg() {
66        let e: anyhow::Error = anyhow::anyhow!("fail");
67        let s = e.display_chain_with_msg("something went wrong");
68        assert!(s.starts_with("Error: something went wrong"));
69        assert!(s.contains("Caused by: fail"));
70    }
71}