use thiserror::Error;
pub(crate) mod classify;
mod code;
pub use code::ErrorCode;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
#[error("Action {code}: {source}")]
Action {
code: ErrorCode,
receipt: Box<crate::ActionReceipt>,
#[source]
source: Box<Error>,
},
#[error("{code}: {message}")]
Coded {
code: ErrorCode,
message: String,
},
#[error(fmt = transport_fmt)]
Transport {
context: String,
#[source]
source: Option<std::io::Error>,
},
#[error(fmt = cdp_fmt)]
Cdp {
method: Option<String>,
code: Option<i64>,
message: String,
},
#[error("Element not found: {0}")]
ElementNotFound(String),
#[error("Element not visible: '{selector}' exists in DOM but is not rendered (hidden, display:none, or off-screen)")]
ElementNotVisible {
selector: String,
},
#[error("Invalid URL: {0}")]
InvalidUrl(String),
#[error("Value mismatch for {selector}: the control holds {actual_chars} characters after filling {expected_chars}")]
ValueMismatch {
selector: String,
expected_chars: usize,
actual_chars: usize,
},
#[error("Serialization error: {0}")]
Serialization(#[from] serde_json::Error),
#[error("Evaluation result exceeds its JSON byte limit of {maximum_bytes}")]
EvaluationTooLarge {
maximum_bytes: usize,
},
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Chrome not found")]
ChromeNotFound,
#[error("Patching error in {operation}: {message}")]
Patching {
operation: String,
message: String,
},
#[error("Retry exhausted after {attempts} attempts: {last_error}")]
RetryExhausted {
attempts: u32,
last_error: String,
#[source]
source: Box<Error>,
},
}
impl Clone for Error {
fn clone(&self) -> Self {
use serde::de::Error as _;
match self {
Self::Action {
code,
receipt,
source,
} => Self::Action {
code: *code,
receipt: receipt.clone(),
source: source.clone(),
},
Self::Coded { code, message } => Self::Coded {
code: *code,
message: message.clone(),
},
Self::Transport { context, source } => Self::Transport {
context: context.clone(),
source: source
.as_ref()
.map(|e| std::io::Error::new(e.kind(), e.to_string())),
},
Self::Cdp {
method,
code,
message,
} => Self::Cdp {
method: method.clone(),
code: *code,
message: message.clone(),
},
Self::ElementNotFound(s) => Self::ElementNotFound(s.clone()),
Self::ElementNotVisible { selector } => Self::ElementNotVisible {
selector: selector.clone(),
},
Self::InvalidUrl(s) => Self::InvalidUrl(s.clone()),
Self::ValueMismatch {
selector,
expected_chars,
actual_chars,
} => Self::ValueMismatch {
selector: selector.clone(),
expected_chars: *expected_chars,
actual_chars: *actual_chars,
},
Self::Serialization(e) => Self::Serialization(serde_json::Error::custom(e.to_string())),
Self::EvaluationTooLarge { maximum_bytes } => Self::EvaluationTooLarge {
maximum_bytes: *maximum_bytes,
},
Self::Io(e) => Self::Io(std::io::Error::new(e.kind(), e.to_string())),
Self::ChromeNotFound => Self::ChromeNotFound,
Self::Patching { operation, message } => Self::Patching {
operation: operation.clone(),
message: message.clone(),
},
Self::RetryExhausted {
attempts,
last_error,
source,
} => Self::RetryExhausted {
attempts: *attempts,
last_error: last_error.clone(),
source: source.clone(),
},
}
}
}
fn cdp_fmt(
method: &Option<String>,
code: &Option<i64>,
message: &str,
f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
match (method, code) {
(Some(m), Some(c)) => write!(f, "CDP error in {}: {} (code {})", m, message, c),
(Some(m), None) => write!(f, "CDP error in {}: {}", m, message),
_ => write!(f, "CDP error: {}", message),
}
}
fn transport_fmt(
context: &str,
source: &Option<std::io::Error>,
f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
match source {
Some(err) => write!(f, "Transport error: {}: {}", context, err),
None => write!(f, "Transport error: {}", context),
}
}
impl Error {
pub fn javascript_exception(details: &serde_json::Value) -> Self {
match serde_json::from_value::<crate::cdp::types::ExceptionDetails>(details.clone()) {
Ok(details) => Self::cdp_msg(details.message()),
Err(_) => Self::cdp_msg("JavaScript exception details unavailable"),
}
}
pub fn transport(context: impl Into<String>) -> Self {
Self::Transport {
context: context.into(),
source: None,
}
}
pub fn transport_io(context: impl Into<String>, source: std::io::Error) -> Self {
Self::Transport {
context: context.into(),
source: Some(source),
}
}
pub fn cdp(method: impl Into<String>, code: i64, message: impl Into<String>) -> Self {
Self::Cdp {
method: Some(method.into()),
code: Some(code),
message: message.into(),
}
}
pub fn cdp_msg(message: impl Into<String>) -> Self {
Self::Cdp {
method: None,
code: None,
message: message.into(),
}
}
pub fn coded(code: ErrorCode, message: impl Into<String>) -> Self {
Self::Coded {
code,
message: message.into(),
}
}
pub fn timeout(message: impl Into<String>) -> Self {
Self::coded(ErrorCode::Timeout, message)
}
pub fn launch(message: impl Into<String>) -> Self {
Self::coded(ErrorCode::LaunchFailed, message)
}
pub(crate) fn navigation(message: impl Into<String>) -> Self {
Self::coded(ErrorCode::NavigationFailed, message)
}
pub(crate) fn invalid_argument(message: impl Into<String>) -> Self {
Self::coded(ErrorCode::InvalidArgument, message)
}
pub(crate) fn decode(message: impl Into<String>) -> Self {
Self::coded(ErrorCode::DecodeFailed, message)
}
pub(crate) fn input_state(message: impl Into<String>) -> Self {
Self::coded(ErrorCode::InputState, message)
}
pub fn code(&self) -> Option<ErrorCode> {
match self {
Self::Coded { code, .. } | Self::Action { code, .. } => Some(*code),
Self::ValueMismatch { .. } => Some(ErrorCode::ValueMismatch),
Self::InvalidUrl(_) => Some(ErrorCode::InvalidUrl),
Self::EvaluationTooLarge { .. } => Some(ErrorCode::ResultTooLarge),
Self::ChromeNotFound => Some(ErrorCode::ChromeNotFound),
_ => None,
}
}
pub fn is_retryable(&self) -> bool {
match self {
Self::Action { code, receipt, .. } => {
receipt.dispatch == crate::DispatchState::NotSent && code.is_transient()
}
Self::Coded { code, .. } => code.is_transient(),
Self::InvalidUrl(_)
| Self::Serialization(_)
| Self::EvaluationTooLarge { .. }
| Self::ChromeNotFound
| Self::ValueMismatch { .. }
| Self::RetryExhausted { .. } => false,
_ => true,
}
}
pub fn patching(operation: impl Into<String>, message: impl Into<String>) -> Self {
Self::Patching {
operation: operation.into(),
message: message.into(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::error::Error as StdError;
#[test]
fn test_transport_io_display_includes_context_and_cause() {
let err = Error::transport_io(
"Failed to connect",
std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "boom"),
);
let msg = format!("{}", err);
assert!(
msg.contains("Failed to connect"),
"missing context in: {msg}"
);
assert!(msg.contains("boom"), "missing io cause in: {msg}");
}
#[test]
fn test_transport_io_exposes_source() {
let err = Error::transport_io(
"Failed to connect",
std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "boom"),
);
assert!(
err.source().is_some(),
"transport_io error should expose its io source"
);
}
#[test]
fn test_cdp_display_with_and_without_context() {
let full = Error::cdp("DOM.resolveNode", -1, "boom");
assert_eq!(
format!("{full}"),
"CDP error in DOM.resolveNode: boom (code -1)"
);
let simple = Error::cdp_msg("no value");
assert_eq!(format!("{simple}"), "CDP error: no value");
}
#[test]
fn test_error_codes_compare_with_their_string_form() {
let error = Error::coded(ErrorCode::HistoryUnavailable, "no entry");
assert_eq!(error.code(), Some(ErrorCode::HistoryUnavailable));
assert!(ErrorCode::HistoryUnavailable == "history_unavailable");
assert_eq!(error.to_string(), "history_unavailable: no entry");
assert_eq!(
serde_json::to_value(ErrorCode::ValueMismatch).unwrap(),
serde_json::json!("value_mismatch")
);
}
#[test]
fn test_permanent_errors_are_not_retryable() {
assert!(!Error::InvalidUrl("x".into()).is_retryable());
assert!(!Error::coded(ErrorCode::AmbiguousTarget, "x").is_retryable());
assert!(!Error::ChromeNotFound.is_retryable());
assert!(Error::timeout("x").is_retryable());
assert!(Error::launch("x").is_retryable());
assert!(Error::decode("x").is_retryable());
assert!(Error::coded(ErrorCode::NavigationFailed, "x").is_retryable());
assert!(!Error::input_state("x").is_retryable());
assert!(!Error::invalid_argument("x").is_retryable());
assert_eq!(Error::timeout("x").code(), Some(ErrorCode::Timeout));
assert_eq!(Error::timeout("x").to_string(), "timeout: x");
assert_eq!(
Error::ChromeNotFound.code(),
Some(ErrorCode::ChromeNotFound)
);
assert_eq!(
Error::InvalidUrl("x".into()).code(),
Some(ErrorCode::InvalidUrl)
);
assert_eq!(
Error::EvaluationTooLarge { maximum_bytes: 1 }.code(),
Some(ErrorCode::ResultTooLarge)
);
assert!(Error::coded(ErrorCode::ActionabilityChanged, "x").is_retryable());
}
#[test]
fn test_value_mismatch_hides_values() {
let error = Error::ValueMismatch {
selector: "#password".into(),
expected_chars: 8,
actual_chars: 6,
};
let text = error.to_string();
assert!(text.contains("#password") && text.contains('8') && text.contains('6'));
}
#[test]
fn test_transport_display_plain_message() {
let err = Error::transport("plain msg");
let msg = format!("{}", err);
assert!(msg.contains("plain msg"), "missing message in: {msg}");
assert!(err.source().is_none());
}
}