1use thiserror::Error;
2
3#[derive(Error, Debug)]
5pub enum BrowserError {
6 #[error("Failed to launch browser: {0}")]
8 LaunchFailed(String),
9
10 #[error("Failed to connect to browser: {0}")]
12 ConnectionFailed(String),
13
14 #[error("Operation timed out: {0}")]
16 Timeout(String),
17
18 #[error("Invalid selector: {0}")]
20 SelectorInvalid(String),
21
22 #[error("Element not found: {0}")]
24 ElementNotFound(String),
25
26 #[error("Failed to parse DOM: {0}")]
28 DomParseFailed(String),
29
30 #[error("Tool '{tool}' execution failed: {reason}")]
32 ToolExecutionFailed { tool: String, reason: String },
33
34 #[error("Invalid argument: {0}")]
36 InvalidArgument(String),
37
38 #[error("Navigation failed: {0}")]
40 NavigationFailed(String),
41
42 #[error("JavaScript evaluation failed: {0}")]
44 EvaluationFailed(String),
45
46 #[error("Screenshot failed: {0}")]
48 ScreenshotFailed(String),
49
50 #[error("Download failed: {0}")]
52 DownloadFailed(String),
53
54 #[error("Tab operation failed: {0}")]
56 TabOperationFailed(String),
57
58 #[error("Chrome error: {0}")]
60 ChromeError(String),
61
62 #[error("JSON error: {0}")]
64 JsonError(#[from] serde_json::Error),
65
66 #[error("IO error: {0}")]
68 IoError(#[from] std::io::Error),
69}
70
71pub type Result<T> = std::result::Result<T, BrowserError>;
73
74impl From<anyhow::Error> for BrowserError {
76 fn from(err: anyhow::Error) -> Self {
77 BrowserError::ChromeError(err.to_string())
78 }
79}
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84
85 #[test]
86 fn test_error_display() {
87 let err = BrowserError::LaunchFailed("Chrome not found".to_string());
88 assert_eq!(
89 err.to_string(),
90 "Failed to launch browser: Chrome not found"
91 );
92 }
93
94 #[test]
95 fn test_tool_execution_error() {
96 let err = BrowserError::ToolExecutionFailed {
97 tool: "navigate".to_string(),
98 reason: "Invalid URL".to_string(),
99 };
100 assert_eq!(
101 err.to_string(),
102 "Tool 'navigate' execution failed: Invalid URL"
103 );
104 }
105
106 #[test]
107 fn test_json_error_conversion() {
108 let json_err = serde_json::from_str::<serde_json::Value>("invalid json");
109 assert!(json_err.is_err());
110
111 let browser_err: BrowserError = json_err.unwrap_err().into();
112 assert!(matches!(browser_err, BrowserError::JsonError(_)));
113 }
114
115 #[test]
116 fn test_result_type_alias() {
117 fn example_function() -> Result<String> {
118 Err(BrowserError::InvalidArgument("test".to_string()))
119 }
120
121 let result = example_function();
122 assert!(result.is_err());
123 }
124}