Skip to main content

rust_robotics_core/
error.rs

1//! Error types for rust_robotics
2
3use alloc::string::String;
4use core::fmt;
5
6/// Main error type for robotics algorithms
7#[derive(Debug)]
8pub enum RoboticsError {
9    /// Path planning failed
10    PlanningError(String),
11    /// State estimation failed
12    EstimationError(String),
13    /// Control computation failed
14    ControlError(String),
15    /// Invalid parameter
16    InvalidParameter(String),
17    /// Numerical computation failed (matrix inversion, etc.)
18    NumericalError(String),
19    /// I/O error
20    #[cfg(feature = "std")]
21    IoError(std::io::Error),
22    /// Visualization error
23    VisualizationError(String),
24}
25
26impl fmt::Display for RoboticsError {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            RoboticsError::PlanningError(msg) => write!(f, "Planning error: {}", msg),
30            RoboticsError::EstimationError(msg) => write!(f, "Estimation error: {}", msg),
31            RoboticsError::ControlError(msg) => write!(f, "Control error: {}", msg),
32            RoboticsError::InvalidParameter(msg) => write!(f, "Invalid parameter: {}", msg),
33            RoboticsError::NumericalError(msg) => write!(f, "Numerical error: {}", msg),
34            #[cfg(feature = "std")]
35            RoboticsError::IoError(e) => write!(f, "I/O error: {}", e),
36            RoboticsError::VisualizationError(msg) => write!(f, "Visualization error: {}", msg),
37        }
38    }
39}
40
41#[cfg(feature = "std")]
42impl std::error::Error for RoboticsError {
43    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
44        match self {
45            RoboticsError::IoError(e) => Some(e),
46            _ => None,
47        }
48    }
49}
50
51#[cfg(feature = "std")]
52impl From<std::io::Error> for RoboticsError {
53    fn from(e: std::io::Error) -> Self {
54        RoboticsError::IoError(e)
55    }
56}
57
58/// Result type alias for robotics operations
59pub type RoboticsResult<T> = Result<T, RoboticsError>;
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64    use alloc::format;
65    use alloc::string::ToString;
66
67    #[test]
68    fn test_error_display() {
69        let err = RoboticsError::PlanningError("No path found".to_string());
70        assert_eq!(format!("{}", err), "Planning error: No path found");
71    }
72
73    #[cfg(feature = "std")]
74    #[test]
75    fn test_error_from_io() {
76        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
77        let err: RoboticsError = io_err.into();
78        assert!(matches!(err, RoboticsError::IoError(_)));
79    }
80}