Skip to main content

cdp_use_rs/
error.rs

1use std::fmt;
2
3/// Errors that can occur when communicating with Chrome via CDP.
4#[derive(Debug)]
5pub enum CdpError {
6    /// CDP protocol error returned by the browser (contains error code and message).
7    Protocol {
8        code: i64,
9        message: String,
10        data: Option<String>,
11    },
12    /// WebSocket connection was closed.
13    ConnectionClosed,
14    /// CDP command timed out waiting for a response.
15    Timeout,
16    /// JSON serialization/deserialization error.
17    Serialization(serde_json::Error),
18    /// WebSocket transport error.
19    WebSocket(tokio_tungstenite::tungstenite::Error),
20}
21
22impl fmt::Display for CdpError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            CdpError::Protocol {
26                code,
27                message,
28                data,
29            } => {
30                write!(f, "CDP protocol error {}: {}", code, message)?;
31                if let Some(d) = data {
32                    write!(f, " ({})", d)?;
33                }
34                Ok(())
35            }
36            CdpError::ConnectionClosed => write!(f, "WebSocket connection closed"),
37            CdpError::Timeout => write!(f, "CDP command timed out"),
38            CdpError::Serialization(e) => write!(f, "Serialization error: {}", e),
39            CdpError::WebSocket(e) => write!(f, "WebSocket error: {}", e),
40        }
41    }
42}
43
44impl std::error::Error for CdpError {
45    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
46        match self {
47            CdpError::Serialization(e) => Some(e),
48            CdpError::WebSocket(e) => Some(e),
49            _ => None,
50        }
51    }
52}
53
54impl From<serde_json::Error> for CdpError {
55    fn from(e: serde_json::Error) -> Self {
56        CdpError::Serialization(e)
57    }
58}
59
60impl From<tokio_tungstenite::tungstenite::Error> for CdpError {
61    fn from(e: tokio_tungstenite::tungstenite::Error) -> Self {
62        CdpError::WebSocket(e)
63    }
64}