Skip to main content

tidepool_gvm/
error.rs

1//! Unified error handling module
2//!
3//! Provides a unified error type and handling for the project.
4
5/// Unified Result type for the project
6pub type Result<T, E = anyhow::Error> = std::result::Result<T, E>;
7
8/// Common error creation macro
9#[macro_export]
10macro_rules! err {
11    ($($arg:tt)*) => { anyhow::anyhow!($($arg)*) };
12}
13
14/// Error handling utility functions
15pub struct ErrorUtils;
16
17impl ErrorUtils {
18    /// Converts an IO error to a user-friendly message
19    pub fn io_error_to_message(err: &std::io::Error) -> String {
20        match err.kind() {
21            std::io::ErrorKind::NotFound => "File or directory not found".to_string(),
22            std::io::ErrorKind::PermissionDenied => "Permission denied".to_string(),
23            std::io::ErrorKind::AlreadyExists => "File or directory already exists".to_string(),
24            std::io::ErrorKind::InvalidInput => "Invalid input".to_string(),
25            _ => format!("IO Error: {err}"),
26        }
27    }
28
29    /// Converts a network error to a user-friendly message
30    pub fn network_error_to_message(err: &reqwest::Error) -> String {
31        if err.is_timeout() {
32            "Network request timed out".to_string()
33        } else if err.is_connect() {
34            "Could not connect to the server".to_string()
35        } else if err.is_status() {
36            format!(
37                "Server returned an error: {}",
38                err.status().map_or("Unknown".to_string(), |s| s.to_string())
39            )
40        } else {
41            format!("Network error: {err}")
42        }
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49    use std::io;
50
51    #[test]
52    fn test_io_error_messages() {
53        let err = io::Error::new(io::ErrorKind::NotFound, "not found");
54        assert_eq!(ErrorUtils::io_error_to_message(&err), "File or directory not found");
55
56        let err = io::Error::new(io::ErrorKind::PermissionDenied, "permission denied");
57        assert_eq!(ErrorUtils::io_error_to_message(&err), "Permission denied");
58    }
59}