Skip to main content

allot_shared/
error.rs

1use std::path::PathBuf;
2
3/// Errors shared by every crate in the workspace.
4#[derive(Debug, thiserror::Error)]
5#[non_exhaustive]
6pub enum Error {
7    /// The configuration file is missing a value or holds an invalid one.
8    #[error("invalid configuration: {0}")]
9    Config(String),
10    /// The configuration file is not valid TOML, has an unknown key, or has a wrongly typed value.
11    #[error("invalid configuration file: {0}")]
12    ConfigParse(#[from] toml::de::Error),
13    /// A configuration file could not be read or holds an invalid value; names the file so
14    /// the user knows what to fix.
15    #[error("{}: {reason}", path.display())]
16    ConfigFile {
17        /// The file that was read.
18        path: PathBuf,
19        /// What was wrong with it.
20        reason: Box<Error>,
21    },
22    /// Reading system or GPU counters failed.
23    #[error("sampling failed: {0}")]
24    Sampler(String),
25    /// A filesystem or process operation failed.
26    #[error(transparent)]
27    Io(#[from] std::io::Error),
28}
29
30/// Result alias using the shared [`Error`].
31pub type Result<T> = std::result::Result<T, Error>;
32
33#[cfg(test)]
34mod tests {
35    use std::io;
36
37    use super::*;
38
39    fn fail_with_io() -> Result<()> {
40        Err(io::Error::new(io::ErrorKind::NotFound, "token file"))?;
41        Ok(())
42    }
43
44    #[test]
45    fn test_error_from_io_converts_with_question_mark() {
46        let error = fail_with_io().unwrap_err();
47        assert!(matches!(error, Error::Io(_)));
48        assert_eq!(error.to_string(), "token file");
49    }
50
51    #[test]
52    fn test_error_config_display_includes_reason() {
53        let error = Error::Config("heartbeat_ttl must be positive".into());
54        assert_eq!(
55            error.to_string(),
56            "invalid configuration: heartbeat_ttl must be positive"
57        );
58    }
59}