Skip to main content

cdp_driver/
error.rs

1//! The crate's error type and [`Result`] alias.
2
3use std::fmt;
4
5/// Errors returned by every fallible operation in this crate.
6#[derive(Debug)]
7pub enum CdpError {
8    /// The CDP WebSocket connection failed or dropped.
9    WebSocket(Box<tokio_tungstenite::tungstenite::Error>),
10    /// A request to Chrome's HTTP endpoint (`/json/*`) failed.
11    Http(reqwest::Error),
12    /// A CDP payload failed to (de)serialize.
13    Json(serde_json::Error),
14    /// A filesystem operation (e.g. writing a screenshot) failed.
15    Io(std::io::Error),
16    /// A URL supplied by the caller or returned by Chrome was malformed or missing.
17    InvalidUrl(String),
18    /// Chrome returned a CDP protocol-level error, or a response was shaped
19    /// unexpectedly.
20    Protocol(String),
21    /// A command or event wait exceeded its configured timeout.
22    Timeout,
23    /// No page target was available to connect to (e.g. `list_targets` returned none).
24    NoTarget,
25}
26
27impl fmt::Display for CdpError {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match self {
30            CdpError::WebSocket(e) => write!(f, "WebSocket error: {e}"),
31            CdpError::Http(e) => write!(f, "HTTP error: {e}"),
32            CdpError::Json(e) => write!(f, "JSON error: {e}"),
33            CdpError::Io(e) => write!(f, "IO error: {e}"),
34            CdpError::InvalidUrl(s) => write!(f, "Invalid URL: {s}"),
35            CdpError::Protocol(s) => write!(f, "Protocol error: {s}"),
36            CdpError::Timeout => write!(f, "Operation timed out"),
37            CdpError::NoTarget => write!(f, "No page target available"),
38        }
39    }
40}
41
42impl std::error::Error for CdpError {}
43
44impl From<tokio_tungstenite::tungstenite::Error> for CdpError {
45    fn from(e: tokio_tungstenite::tungstenite::Error) -> Self {
46        CdpError::WebSocket(Box::new(e))
47    }
48}
49
50impl From<reqwest::Error> for CdpError {
51    fn from(e: reqwest::Error) -> Self {
52        CdpError::Http(e)
53    }
54}
55
56impl From<serde_json::Error> for CdpError {
57    fn from(e: serde_json::Error) -> Self {
58        CdpError::Json(e)
59    }
60}
61
62impl From<std::io::Error> for CdpError {
63    fn from(e: std::io::Error) -> Self {
64        CdpError::Io(e)
65    }
66}
67
68/// Convenience alias for `std::result::Result<T, CdpError>`.
69pub type Result<T> = std::result::Result<T, CdpError>;