pub struct ErrorContext {
pub provider: String,
pub endpoint: String,
pub request_id: Option<String>,
pub timestamp: DateTime<Utc>,
pub retry_count: u32,
pub suggested_action: SuggestedAction,
}
Expand description
Context information for error tracking
Fields§
§provider: String
AI provider that generated the error
endpoint: String
API endpoint that was called
request_id: Option<String>
Request ID for tracking
timestamp: DateTime<Utc>
Timestamp when the error occurred
retry_count: u32
Number of retry attempts
suggested_action: SuggestedAction
Suggested action to take
Implementations§
Source§impl ErrorContext
impl ErrorContext
Sourcepub fn new(provider: String, endpoint: String) -> Self
pub fn new(provider: String, endpoint: String) -> Self
Create a new error context
Examples found in repository?
examples/resilience_example.rs (line 153)
140async fn demonstrate_error_handling() -> Result<(), Box<dyn std::error::Error>> {
141 let error_manager = ErrorRecoveryManager::new();
142
143 // Simulate different types of errors
144 let errors = vec![
145 ("Rate Limit", ai_lib::types::AiLibError::RateLimitExceeded("API rate limit exceeded".to_string())),
146 ("Network", ai_lib::types::AiLibError::NetworkError("Connection timeout".to_string())),
147 ("Authentication", ai_lib::types::AiLibError::AuthenticationError("Invalid API key".to_string())),
148 ("Context Length", ai_lib::types::AiLibError::ContextLengthExceeded("Request too long".to_string())),
149 ];
150
151 println!("Error Handling and Pattern Analysis:");
152 for (error_type, error) in errors {
153 let context = ErrorContext::new("demo_provider".to_string(), "/demo/endpoint".to_string());
154 let result = error_manager.handle_error(&error, &context).await;
155
156 println!(" {} Error: {}", error_type, error);
157 println!(" Suggested Action: {:?}", context.suggested_action);
158 println!(" Recovery Result: {}", if result.is_ok() { "Success" } else { "Failed" });
159 }
160
161 // Show error statistics
162 let stats = error_manager.get_error_statistics();
163 println!("\nError Statistics:");
164 println!(" Total Errors: {}", stats.total_errors);
165 println!(" Unique Error Types: {}", stats.unique_error_types);
166 println!(" Most Common: {:?}", stats.most_common_error);
167
168 // Show error patterns
169 let patterns = error_manager.get_error_patterns();
170 for (error_type, pattern) in patterns {
171 println!(" {:?}: {} occurrences, {:.2} errors/min",
172 error_type, pattern.count, pattern.frequency);
173 }
174
175 Ok(())
176}
177
178async fn demonstrate_integrated_resilience() -> Result<(), Box<dyn std::error::Error>> {
179 // Create all resilience components
180 let circuit_breaker = CircuitBreaker::new(CircuitBreakerConfig::development());
181 let rate_limiter = TokenBucket::new(RateLimiterConfig::development());
182 let error_manager = ErrorRecoveryManager::new();
183
184 println!("Integrated Resilience Components:");
185 println!(" Circuit Breaker: {:?}", circuit_breaker.state());
186 println!(" Rate Limiter: {:.1}% success rate", rate_limiter.success_rate());
187 println!(" Error Manager: {} total errors", error_manager.get_error_statistics().total_errors);
188
189 // Simulate a resilient operation
190 println!("\nSimulating resilient operation:");
191 for i in 1..=5 {
192 println!(" Operation {}:", i);
193
194 // Step 1: Rate limiting
195 match rate_limiter.acquire(1).await {
196 Ok(_) => println!(" ✅ Rate limit passed"),
197 Err(e) => {
198 println!(" ❌ Rate limited: {}", e);
199 continue;
200 }
201 }
202
203 // Step 2: Circuit breaker protection
204 let result = circuit_breaker.call(async {
205 // Simulate API call with occasional failures
206 if i % 4 == 0 {
207 Err(ai_lib::types::AiLibError::ProviderError("Simulated provider error".to_string()))
208 } else {
209 Ok(format!("API response {}", i))
210 }
211 }).await;
212
213 // Step 3: Error handling
214 match result {
215 Ok(response) => {
216 println!(" ✅ Success: {}", response);
217 rate_limiter.adjust_rate(true);
218 }
219 Err(e) => {
220 println!(" ❌ Failed: {}", e);
221 rate_limiter.adjust_rate(false);
222
223 // Convert CircuitBreakerError to AiLibError for error manager
224 let ai_error = match e {
225 CircuitBreakerError::Underlying(err) => err,
226 CircuitBreakerError::CircuitOpen(msg) => ai_lib::types::AiLibError::ProviderError(msg),
227 CircuitBreakerError::RequestTimeout(msg) => ai_lib::types::AiLibError::TimeoutError(msg),
228 CircuitBreakerError::Disabled => ai_lib::types::AiLibError::ConfigurationError("Circuit breaker disabled".to_string()),
229 };
230
231 let context = ErrorContext::new("demo_provider".to_string(), "/demo/endpoint".to_string());
232 let _ = error_manager.handle_error(&ai_error, &context).await;
233 }
234 }
235
236 // Show current state
237 println!(" State: CB={:?}, RL={:.1}%",
238 circuit_breaker.state(), rate_limiter.success_rate());
239 }
240
241 Ok(())
242}
Sourcepub fn with_retry(self, retry_count: u32) -> Self
pub fn with_retry(self, retry_count: u32) -> Self
Create error context with retry information
Sourcepub fn with_request_id(self, request_id: String) -> Self
pub fn with_request_id(self, request_id: String) -> Self
Create error context with request ID
Trait Implementations§
Source§impl Clone for ErrorContext
impl Clone for ErrorContext
Source§fn clone(&self) -> ErrorContext
fn clone(&self) -> ErrorContext
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source
. Read moreSource§impl Debug for ErrorContext
impl Debug for ErrorContext
Source§impl<'de> Deserialize<'de> for ErrorContext
impl<'de> Deserialize<'de> for ErrorContext
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
Auto Trait Implementations§
impl Freeze for ErrorContext
impl RefUnwindSafe for ErrorContext
impl Send for ErrorContext
impl Sync for ErrorContext
impl Unpin for ErrorContext
impl UnwindSafe for ErrorContext
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more