Skip to main content

mojentic/
error.rs

1//! Error types and result aliases for the Mojentic library.
2//!
3//! This module defines the core error type [`MojenticError`] and the [`Result`] type alias
4//! used throughout the library. All public APIs that can fail return `Result<T>` for
5//! consistent error handling.
6
7use thiserror::Error;
8
9#[derive(Error, Debug)]
10pub enum MojenticError {
11    /// Recovery options rejected before any request can be dispatched.
12    #[error("{0}")]
13    InvalidRecoveryPolicy(#[from] crate::llm::recovery::RecoveryPolicyError),
14    /// Structured opt-in completion recovery failure.
15    #[error("{0}")]
16    Recovery(Box<crate::llm::recovery::RecoveryError>),
17    #[error("LLM gateway error: {0}")]
18    GatewayError(String),
19
20    #[error("API error: {0}")]
21    ApiError(String),
22
23    #[error("Serialization error: {0}")]
24    SerializationError(#[from] serde_json::Error),
25
26    #[error("HTTP error: {0}")]
27    HttpError(#[from] reqwest::Error),
28
29    #[error("Tool error: {0}")]
30    ToolError(String),
31
32    #[error("Model not supported: {0}")]
33    ModelNotSupported(String),
34
35    #[error("Invalid configuration: {0}")]
36    ConfigError(String),
37
38    #[error("IO error: {0}")]
39    IoError(#[from] std::io::Error),
40
41    #[error("Event processing error: {0}")]
42    EventError(String),
43
44    #[error("Agent error: {0}")]
45    AgentError(String),
46
47    #[error("Dispatcher error: {0}")]
48    DispatcherError(String),
49
50    #[error("Timeout error: {0}")]
51    TimeoutError(String),
52
53    #[error("Invalid argument: {0}")]
54    InvalidArgument(String),
55
56    #[error("Parse error: {0}")]
57    ParseError(String),
58
59    #[error("Tool execution error: {0}")]
60    ToolExecutionError(String),
61
62    #[error("Runtime error: {0}")]
63    RuntimeError(String),
64
65    #[error("Max tool iterations exceeded: limit {limit}")]
66    MaxToolIterationsExceeded { limit: usize },
67
68    #[error("Event handler error: {0}")]
69    HandlerError(String),
70
71    /// Returned when a tool aborts early because its [`crate::llm::tools::ToolRunCtx`]
72    /// cancellation token was signalled (e.g. barge-in, manual `interrupt()`).
73    #[error("Cancelled")]
74    Cancelled,
75}
76
77pub type Result<T> = std::result::Result<T, MojenticError>;
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82
83    #[test]
84    fn test_gateway_error_display() {
85        let err = MojenticError::GatewayError("connection failed".to_string());
86        assert_eq!(err.to_string(), "LLM gateway error: connection failed");
87    }
88
89    #[test]
90    fn test_api_error_display() {
91        let err = MojenticError::ApiError("rate limit exceeded".to_string());
92        assert_eq!(err.to_string(), "API error: rate limit exceeded");
93    }
94
95    #[test]
96    fn test_tool_error_display() {
97        let err = MojenticError::ToolError("invalid parameters".to_string());
98        assert_eq!(err.to_string(), "Tool error: invalid parameters");
99    }
100
101    #[test]
102    fn test_model_not_supported_display() {
103        let err = MojenticError::ModelNotSupported("gpt-5".to_string());
104        assert_eq!(err.to_string(), "Model not supported: gpt-5");
105    }
106
107    #[test]
108    fn test_config_error_display() {
109        let err = MojenticError::ConfigError("missing API key".to_string());
110        assert_eq!(err.to_string(), "Invalid configuration: missing API key");
111    }
112
113    #[test]
114    fn test_serialization_error_conversion() {
115        let json_err = serde_json::from_str::<serde_json::Value>("invalid json").unwrap_err();
116        let err: MojenticError = json_err.into();
117
118        match err {
119            MojenticError::SerializationError(_) => {}
120            _ => panic!("Expected SerializationError"),
121        }
122    }
123
124    #[test]
125    fn test_http_error_conversion() {
126        // Create a reqwest error by building an invalid request
127        let invalid_url = reqwest::Url::parse("http://").unwrap_err();
128        // Test that we can convert a URL parse error into our error type
129        let err = MojenticError::ApiError(invalid_url.to_string());
130        assert!(err.to_string().contains("API error"));
131    }
132
133    #[test]
134    fn test_io_error_conversion() {
135        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
136        let err: MojenticError = io_err.into();
137
138        match err {
139            MojenticError::IoError(_) => {}
140            _ => panic!("Expected IoError"),
141        }
142    }
143
144    #[test]
145    fn test_error_debug() {
146        let err = MojenticError::ToolError("test".to_string());
147        let debug_str = format!("{:?}", err);
148        assert!(debug_str.contains("ToolError"));
149    }
150
151    #[test]
152    fn test_max_tool_iterations_exceeded_display() {
153        let err = MojenticError::MaxToolIterationsExceeded { limit: 10 };
154        assert_eq!(err.to_string(), "Max tool iterations exceeded: limit 10");
155    }
156
157    #[test]
158    fn test_handler_error_display() {
159        let err = MojenticError::HandlerError("callback panicked".to_string());
160        assert_eq!(err.to_string(), "Event handler error: callback panicked");
161    }
162
163    #[test]
164    fn test_result_type() {
165        let ok_result: Result<i32> = Ok(42);
166        assert!(ok_result.is_ok());
167        if let Ok(value) = ok_result {
168            assert_eq!(value, 42);
169        }
170
171        let err_result: Result<i32> = Err(MojenticError::ToolError("test".to_string()));
172        assert!(err_result.is_err());
173    }
174}