Skip to main content

nym_common/
error.rs

1// Copyright 2016-2024 Mullvad VPN AB. All Rights Reserved.
2// Copyright 2024 Nym Technologies SA <contact@nymtech.net>
3// SPDX-License-Identifier: GPL-3.0-only
4
5use std::{error::Error, fmt, fmt::Write};
6use tracing::error;
7
8/// Used to generate string representations of error chains.
9pub trait ErrorExt {
10    /// Creates a string representation of the entire error chain.
11    fn display_chain(&self) -> String;
12
13    /// Like [Self::display_chain] but with an extra message at the start of the chain.
14    fn display_chain_with_msg<S: AsRef<str>>(&self, msg: S) -> String;
15}
16
17impl<E: Error> ErrorExt for E {
18    fn display_chain(&self) -> String {
19        let mut s = format!("Error: {self}");
20        let mut source = self.source();
21        while let Some(error) = source {
22            if let Err(err) = write!(&mut s, "\nCaused by: {error}") {
23                error!("error formatting failure: {err}");
24            }
25            source = error.source();
26        }
27        s
28    }
29
30    fn display_chain_with_msg<S: AsRef<str>>(&self, msg: S) -> String {
31        let mut s = format!("Error: {}\nCaused by: {}", msg.as_ref(), self);
32        let mut source = self.source();
33        while let Some(error) = source {
34            if let Err(err) = write!(&mut s, "\nCaused by: {error}") {
35                error!("error formatting failure: {err}");
36            }
37            source = error.source();
38        }
39        s
40    }
41}
42
43#[macro_export]
44macro_rules! trace_err_chain {
45    ($err:expr) => {
46        tracing::error!("{}", $crate::ErrorExt::display_chain(&$err));
47    };
48    ($err:expr, $($args:tt)*) => {
49        tracing::error!("{}", $crate::ErrorExt::display_chain_with_msg(&$err, ::std::format!($($args)*)))
50    };
51}
52
53#[derive(Debug)]
54pub struct BoxedError(Box<dyn Error + 'static + Send>);
55
56impl fmt::Display for BoxedError {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        self.0.fmt(f)
59    }
60}
61
62impl Error for BoxedError {
63    fn source(&self) -> Option<&(dyn Error + 'static)> {
64        self.0.source()
65    }
66}
67
68impl BoxedError {
69    pub fn new(error: impl Error + 'static + Send) -> Self {
70        BoxedError(Box::new(error))
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use tracing_test::traced_test;
77
78    use std::{io, path::PathBuf};
79
80    #[test]
81    #[traced_test]
82    fn test_trace_err_chain() {
83        trace_err_chain!(io::Error::other("file not found"));
84        assert!(logs_contain("Error: file not found"));
85    }
86
87    #[test]
88    #[traced_test]
89    fn test_trace_err_chain_with_msg() {
90        trace_err_chain!(io::Error::other("file not found"), "failed to open file");
91        assert!(logs_contain("Error: failed to open file"));
92        // todo: fix once it supports multiline messages
93        // https://github.com/dbrgn/tracing-test/issues/48
94        // assert!(logs_contain("Caused by: file not found"));
95    }
96
97    #[test]
98    #[traced_test]
99    fn test_trace_err_chain_with_msgfmt() {
100        trace_err_chain!(
101            io::Error::other("file not found"),
102            "failed to open file: {}",
103            PathBuf::from("test.txt").display()
104        );
105        assert!(logs_contain("Error: failed to open file: test.txt"));
106        // todo: fix once it supports multiline messages
107        // https://github.com/dbrgn/tracing-test/issues/48
108        // assert!(logs_contain("Caused by: file not found"));
109    }
110}