use std::fmt;
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorCode {
ActionTimeout,
Timeout,
LaunchFailed,
ChromeNotFound,
InvalidUrl,
ResultTooLarge,
DecodeFailed,
ActionFailed,
InputState,
UnsupportedInput,
InvalidInputValue,
TargetUnavailable,
TargetStale,
AmbiguousTarget,
ActionabilityChanged,
HistoryUnavailable,
ExpectationRequired,
ExpectationAlreadySatisfied,
InvalidExpectation,
InvalidTimeout,
InvalidArgument,
AmbiguousDestination,
NavigationFailed,
NavigationAborted,
ValueMismatch,
DownloadBusy,
DownloadUnsupported,
Unsupported,
PreconditionFailed,
Busy,
InvalidState,
CleanupUncertain,
ElementNotFound,
ElementNotVisible,
CdpError,
Transport,
Serialization,
Io,
Patching,
RetryExhausted,
}
impl ErrorCode {
pub(crate) const ALL: &[Self] = &[
Self::ActionTimeout,
Self::Timeout,
Self::LaunchFailed,
Self::ChromeNotFound,
Self::InvalidUrl,
Self::ResultTooLarge,
Self::DecodeFailed,
Self::ActionFailed,
Self::InputState,
Self::UnsupportedInput,
Self::InvalidInputValue,
Self::TargetUnavailable,
Self::TargetStale,
Self::AmbiguousTarget,
Self::ActionabilityChanged,
Self::HistoryUnavailable,
Self::ExpectationRequired,
Self::ExpectationAlreadySatisfied,
Self::InvalidExpectation,
Self::InvalidTimeout,
Self::InvalidArgument,
Self::AmbiguousDestination,
Self::NavigationFailed,
Self::NavigationAborted,
Self::ValueMismatch,
Self::DownloadBusy,
Self::DownloadUnsupported,
Self::Unsupported,
Self::PreconditionFailed,
Self::Busy,
Self::InvalidState,
Self::CleanupUncertain,
Self::ElementNotFound,
Self::ElementNotVisible,
Self::CdpError,
Self::Transport,
Self::Serialization,
Self::Io,
Self::Patching,
Self::RetryExhausted,
];
pub const fn as_str(self) -> &'static str {
match self {
Self::ActionTimeout => "action_timeout",
Self::Timeout => "timeout",
Self::LaunchFailed => "launch_failed",
Self::ChromeNotFound => "chrome_not_found",
Self::InvalidUrl => "invalid_url",
Self::ResultTooLarge => "result_too_large",
Self::DecodeFailed => "decode_failed",
Self::ActionFailed => "action_failed",
Self::InputState => "input_state",
Self::UnsupportedInput => "unsupported_input",
Self::InvalidInputValue => "invalid_input_value",
Self::TargetUnavailable => "target_unavailable",
Self::TargetStale => "target_stale",
Self::AmbiguousTarget => "ambiguous_target",
Self::ActionabilityChanged => "actionability_changed",
Self::HistoryUnavailable => "history_unavailable",
Self::ExpectationRequired => "expectation_required",
Self::ExpectationAlreadySatisfied => "expectation_already_satisfied",
Self::InvalidExpectation => "invalid_expectation",
Self::InvalidTimeout => "invalid_timeout",
Self::InvalidArgument => "invalid_argument",
Self::AmbiguousDestination => "ambiguous_destination",
Self::NavigationFailed => "navigation_failed",
Self::NavigationAborted => "navigation_aborted",
Self::ValueMismatch => "value_mismatch",
Self::DownloadBusy => "download_busy",
Self::DownloadUnsupported => "download_unsupported",
Self::Unsupported => "unsupported",
Self::PreconditionFailed => "precondition_failed",
Self::Busy => "busy",
Self::InvalidState => "invalid_state",
Self::CleanupUncertain => "cleanup_uncertain",
Self::ElementNotFound => "element_not_found",
Self::ElementNotVisible => "element_not_visible",
Self::CdpError => "cdp_error",
Self::Transport => "transport",
Self::Serialization => "serialization",
Self::Io => "io",
Self::Patching => "patching",
Self::RetryExhausted => "retry_exhausted",
}
}
pub const fn is_transient(self) -> bool {
matches!(
self,
Self::ActionTimeout
| Self::Timeout
| Self::LaunchFailed
| Self::DecodeFailed
| Self::TargetUnavailable
| Self::ActionabilityChanged
| Self::NavigationFailed
| Self::NavigationAborted
| Self::DownloadBusy
| Self::Busy
| Self::PreconditionFailed
| Self::ActionFailed
| Self::ElementNotFound
| Self::ElementNotVisible
| Self::CdpError
| Self::Transport
| Self::Io
| Self::Patching
)
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl From<ErrorCode> for String {
fn from(code: ErrorCode) -> Self {
code.as_str().to_owned()
}
}
impl PartialEq<str> for ErrorCode {
fn eq(&self, other: &str) -> bool {
self.as_str() == other
}
}
impl PartialEq<&str> for ErrorCode {
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
impl PartialEq<ErrorCode> for &str {
fn eq(&self, other: &ErrorCode) -> bool {
*self == other.as_str()
}
}
impl serde::Serialize for ErrorCode {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl FromStr for ErrorCode {
type Err = crate::Error;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Self::ALL
.iter()
.copied()
.find(|code| code.as_str() == text)
.ok_or_else(|| crate::Error::invalid_argument(format!("unknown error code {text:?}")))
}
}
impl<'de> serde::Deserialize<'de> for ErrorCode {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
String::deserialize(deserializer)?
.parse()
.map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::ErrorCode;
fn source_codes() -> Vec<&'static str> {
include_str!("code.rs")
.lines()
.filter_map(|l| l.trim().strip_prefix("Self::")?.split_once(" => "))
.map(|(_, rest)| rest.trim_matches(|c| c == '"' || c == ','))
.collect()
}
#[test]
fn every_code_round_trips() {
let codes = source_codes();
assert_eq!(codes.len(), ErrorCode::ALL.len());
for text in codes {
let code: ErrorCode = text.parse().unwrap();
assert_eq!(code.as_str(), text);
assert!(code == text && text == code);
let json = serde_json::to_value(code).unwrap();
assert_eq!(json, serde_json::json!(text));
assert_eq!(serde_json::from_value::<ErrorCode>(json).unwrap(), code);
}
let unique: std::collections::HashSet<_> = ErrorCode::ALL.iter().collect();
assert_eq!(unique.len(), ErrorCode::ALL.len());
let error = "nope".parse::<ErrorCode>().unwrap_err();
assert_eq!(error.code(), ErrorCode::InvalidArgument);
let error = serde_json::from_value::<ErrorCode>(serde_json::json!("nope")).unwrap_err();
assert_eq!(
error.to_string(),
"invalid_argument: unknown error code \"nope\""
);
}
#[test]
fn doc_table_lists_every_code() {
let table: Vec<&str> = include_str!("code.rs")
.lines()
.filter(|l| l.starts_with("/// |"))
.collect();
let codes = source_codes();
assert!(codes.len() > 30, "{codes:?}");
for code in codes {
let quoted = format!("`{code}`");
assert!(
table.iter().any(|l| l.contains("ed)),
"{code} missing from the table"
);
}
}
}