Skip to main content

metis_docs_tui/error/
error_handler.rs

1use super::AppError;
2
3/// Centralized error handler for the application
4pub struct ErrorHandler {
5    current_error: Option<AppError>,
6}
7
8impl ErrorHandler {
9    pub fn new() -> Self {
10        Self {
11            current_error: None,
12        }
13    }
14
15    pub fn handle_error(&mut self, error: AppError) {
16        // Store the error for UI display
17        self.current_error = Some(error);
18    }
19
20    /// Handle common error patterns and provide user-friendly messages
21    pub fn handle_with_context(&mut self, error: AppError, context: &str) {
22        let contextual_error = match error {
23            AppError::WorkspaceError(msg) => {
24                AppError::WorkspaceError(format!("{}: {}", context, msg))
25            }
26            AppError::DocumentError(msg) => {
27                AppError::DocumentError(format!("{}: {}", context, msg))
28            }
29            AppError::ValidationError(msg) => {
30                AppError::ValidationError(format!("{}: {}", context, msg))
31            }
32            AppError::IoError(msg) => AppError::IoError(format!("{}: {}", context, msg)),
33            AppError::DatabaseError(msg) => {
34                AppError::DatabaseError(format!("{}: {}", context, msg))
35            }
36            AppError::UserInputError(msg) => {
37                AppError::UserInputError(format!("{}: {}", context, msg))
38            }
39        };
40
41        self.handle_error(contextual_error);
42    }
43
44    /// Convert various error types to user-friendly messages
45    pub fn get_user_friendly_message(&self) -> Option<String> {
46        self.current_error.as_ref().map(|error| match error {
47            AppError::WorkspaceError(msg) => {
48                if msg.contains("not in a Metis workspace") {
49                    "Run 'metis init' to create a workspace".to_string()
50                } else if msg.contains("database missing") {
51                    "Run 'metis sync' to initialize the database".to_string()
52                } else {
53                    format!("Workspace issue: {}", msg)
54                }
55            }
56            AppError::DocumentError(msg) => {
57                if msg.contains("parent") {
58                    "Invalid parent document selected".to_string()
59                } else {
60                    format!("Document issue: {}", msg)
61                }
62            }
63            AppError::ValidationError(msg) => {
64                format!("Validation failed: {}", msg)
65            }
66            AppError::UserInputError(msg) => {
67                format!("Invalid input: {}", msg)
68            }
69            _ => error.to_string(),
70        })
71    }
72}
73
74impl Default for ErrorHandler {
75    fn default() -> Self {
76        Self::new()
77    }
78}