use std::{convert::Infallible, error, fmt};
use url::Url;
use crate::redact::sanitize_url;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ErrorKind {
Request,
Url,
Runtime,
Dns,
Connect,
Tls,
Proxy,
Timeout,
Redirect,
Retry,
BodyIo,
BodyLimit,
Decoding,
Transport,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RedirectError {
TooManyHops {
limit: u32,
followed: u32,
},
Cycle {
followed: u32,
},
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RetryError {
Exhausted {
attempts: u8,
last: ErrorKind,
},
}
#[derive(Clone)]
pub struct Error {
kind: ErrorKind,
message: String,
redirect: Option<RedirectError>,
retry: Option<RetryError>,
sanitized_url: Option<String>,
}
pub type Result<T> = std::result::Result<T, Error>;
impl Error {
#[must_use]
pub fn from_kind(kind: ErrorKind) -> Self {
Self::new(kind, default_message(kind))
}
pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
let message = message.into();
Self::with_message(kind, format!("{}: {message}", KindDisplay(kind)))
}
fn with_message(kind: ErrorKind, message: String) -> Self {
Self {
kind,
message,
redirect: None,
retry: None,
sanitized_url: None,
}
}
pub(crate) fn url(reason: &'static str) -> Self {
Self::invalid_url(reason.to_owned())
}
pub(crate) fn invalid_request(reason: &'static str) -> Self {
Self::with_message(ErrorKind::Request, format!("invalid request: {reason}"))
}
pub(crate) fn invalid_response(reason: &'static str) -> Self {
Self::with_message(ErrorKind::Transport, format!("invalid response: {reason}"))
}
fn invalid_url(reason: String) -> Self {
Self::with_message(ErrorKind::Url, format!("invalid URL: {reason}"))
}
fn invalid_header_name(reason: String) -> Self {
Self::with_message(ErrorKind::Request, format!("invalid header name: {reason}"))
}
fn invalid_header_value(reason: String) -> Self {
Self::with_message(
ErrorKind::Request,
format!("invalid header value: {reason}"),
)
}
fn form(reason: String) -> Self {
Self::with_message(ErrorKind::Request, format!("form error: {reason}"))
}
fn io(reason: String) -> Self {
Self::with_message(ErrorKind::BodyIo, format!("body I/O error: {reason}"))
}
fn classified(
kind: ErrorKind,
message: impl Into<String>,
redirect: Option<RedirectError>,
retry: Option<RetryError>,
) -> Self {
let mut error = Self::new(kind, message);
error.redirect = redirect;
error.retry = retry;
error
}
#[must_use]
pub fn kind(&self) -> ErrorKind {
self.kind
}
#[must_use]
pub fn redirect_error(&self) -> Option<RedirectError> {
self.redirect
}
#[must_use]
pub fn retry_error(&self) -> Option<RetryError> {
self.retry
}
#[must_use]
pub fn sanitized_url(&self) -> Option<&str> {
self.sanitized_url.as_deref()
}
pub(crate) fn from_reqwest(error: reqwest::Error) -> Self {
let mut source = error::Error::source(&error);
while let Some(current) = source {
if let Some(owned) = current.downcast_ref::<Self>() {
return owned.clone();
}
source = current.source();
}
let kind = if error.is_timeout() {
ErrorKind::Timeout
} else if let Some(kind) = classify_backend_sources(&error) {
kind
} else if error.is_connect() {
ErrorKind::Connect
} else if error.is_builder() {
ErrorKind::Request
} else if error.is_decode() {
ErrorKind::Decoding
} else if error.is_body() {
ErrorKind::BodyIo
} else if error.is_redirect() {
ErrorKind::Redirect
} else {
ErrorKind::Transport
};
let message = match kind {
ErrorKind::Timeout => "request deadline exceeded",
ErrorKind::Connect => "connection failed",
ErrorKind::Dns => "DNS resolution failed",
ErrorKind::Tls => "TLS negotiation failed",
ErrorKind::Proxy => "proxy communication failed",
ErrorKind::Request => "request could not be encoded",
ErrorKind::Decoding => "response decoding failed",
ErrorKind::BodyIo => "body stream failed",
ErrorKind::Redirect => "redirect processing failed",
_ => "request transport failed",
};
let mut classified = Self::new(kind, message);
if let Some(url) = error.url() {
classified.set_sanitized_url(url);
}
classified
}
pub(crate) fn proxy(_error: impl error::Error + Send + Sync + 'static) -> Self {
Self::new(ErrorKind::Proxy, "proxy configuration is invalid")
}
pub(crate) fn body_limit(limit: usize) -> Self {
Self::new(
ErrorKind::BodyLimit,
format!("decoded body exceeded the {limit}-byte limit"),
)
}
pub(crate) fn timeout(message: &'static str) -> Self {
Self::new(ErrorKind::Timeout, message)
}
pub(crate) fn redirect(error: RedirectError, url: &Url) -> Self {
let message = match error {
RedirectError::TooManyHops { .. } => "redirect hop limit exceeded",
RedirectError::Cycle { .. } => "redirect cycle detected",
};
let mut result = Self::classified(ErrorKind::Redirect, message, Some(error), None);
result.set_sanitized_url(url);
result
}
pub(crate) fn retry_exhausted(attempts: u8, last_kind: ErrorKind, url: &Url) -> Self {
let retry = RetryError::Exhausted {
attempts,
last: last_kind,
};
let mut result = Self::classified(
ErrorKind::Retry,
format!(
"retry attempts exhausted after {attempts} attempts; last failure was {}",
KindDisplay(last_kind)
),
None,
Some(retry),
);
result.set_sanitized_url(url);
result
}
fn set_sanitized_url(&mut self, url: &Url) {
self.sanitized_url = Some(sanitize_url(url));
}
}
fn classify_backend_sources(error: &reqwest::Error) -> Option<ErrorKind> {
let mut source = error::Error::source(error);
while let Some(current) = source {
if let Some(kind) = classify_typed_source(current) {
return Some(kind);
}
source = current.source();
}
None
}
fn classify_typed_source(source: &(dyn error::Error + 'static)) -> Option<ErrorKind> {
#[cfg(feature = "rustls")]
if source.downcast_ref::<rustls::Error>().is_some() {
return Some(ErrorKind::Tls);
}
source
.downcast_ref::<std::io::Error>()
.and_then(std::io::Error::get_ref)
.and_then(|inner| classify_typed_source(inner))
}
impl fmt::Debug for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Error")
.field("kind", &self.kind())
.field("message", &self.to_string())
.field("redirect", &self.redirect_error())
.field("retry", &self.retry_error())
.field("sanitized_url", &self.sanitized_url())
.finish()
}
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)?;
if let Some(url) = &self.sanitized_url {
write!(formatter, " ({url})")?;
}
Ok(())
}
}
impl error::Error for Error {}
impl From<url::ParseError> for Error {
fn from(error: url::ParseError) -> Self {
Self::invalid_url(error.to_string())
}
}
impl From<http::header::InvalidHeaderName> for Error {
fn from(error: http::header::InvalidHeaderName) -> Self {
Self::invalid_header_name(error.to_string())
}
}
impl From<http::header::InvalidHeaderValue> for Error {
fn from(error: http::header::InvalidHeaderValue) -> Self {
Self::invalid_header_value(error.to_string())
}
}
impl From<Infallible> for Error {
fn from(error: Infallible) -> Self {
match error {}
}
}
impl From<serde_urlencoded::ser::Error> for Error {
fn from(_error: serde_urlencoded::ser::Error) -> Self {
Self::form("form serialization failed".to_owned())
}
}
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
Self::io(error.kind().to_string())
}
}
struct KindDisplay(ErrorKind);
fn default_message(kind: ErrorKind) -> &'static str {
match kind {
ErrorKind::Request => "request failed",
ErrorKind::Url => "URL processing failed",
ErrorKind::Runtime => "asynchronous runtime is unavailable",
ErrorKind::Dns => "DNS resolution failed",
ErrorKind::Connect => "connection failed",
ErrorKind::Tls => "TLS operation failed",
ErrorKind::Proxy => "proxy operation failed",
ErrorKind::Timeout => "operation timed out",
ErrorKind::Redirect => "redirect processing failed",
ErrorKind::Retry => "retry processing failed",
ErrorKind::BodyIo => "body stream failed",
ErrorKind::BodyLimit => "body limit exceeded",
ErrorKind::Decoding => "response decoding failed",
ErrorKind::Transport => "transport failed",
}
}
impl fmt::Display for KindDisplay {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let value = match self.0 {
ErrorKind::Request => "request error",
ErrorKind::Url => "URL error",
ErrorKind::Runtime => "runtime error",
ErrorKind::Dns => "DNS error",
ErrorKind::Connect => "connect error",
ErrorKind::Tls => "TLS error",
ErrorKind::Proxy => "proxy error",
ErrorKind::Timeout => "timeout",
ErrorKind::Redirect => "redirect error",
ErrorKind::Retry => "retry error",
ErrorKind::BodyIo => "body I/O error",
ErrorKind::BodyLimit => "body limit error",
ErrorKind::Decoding => "decoding error",
ErrorKind::Transport => "transport error",
};
formatter.write_str(value)
}
}
#[cfg(test)]
mod describe_error {
use super::*;
#[test]
fn it_errors_have_stable_classifications() {
for kind in [
ErrorKind::Request,
ErrorKind::Url,
ErrorKind::Runtime,
ErrorKind::Dns,
ErrorKind::Connect,
ErrorKind::Tls,
ErrorKind::Proxy,
ErrorKind::Timeout,
ErrorKind::Redirect,
ErrorKind::Retry,
ErrorKind::BodyIo,
ErrorKind::BodyLimit,
ErrorKind::Decoding,
ErrorKind::Transport,
] {
assert_eq!(Error::from_kind(kind).kind(), kind);
}
assert_eq!(
Error::invalid_request("missing URL").kind(),
ErrorKind::Request
);
assert_eq!(Error::body_limit(4).kind(), ErrorKind::BodyLimit);
assert_eq!(Error::timeout("late").kind(), ErrorKind::Timeout);
}
#[test]
fn it_error_urls_remove_userinfo_query_and_fragment() {
let url = Url::parse("https://user:pass@example.com/path?token=secret#part").unwrap();
let error = Error::redirect(RedirectError::Cycle { followed: 2 }, &url);
let debug = format!("{error:?}");
assert_eq!(error.sanitized_url(), Some("https://example.com/path"));
assert!(!debug.contains("user"));
assert!(!debug.contains("pass"));
assert!(!debug.contains("secret"));
}
#[test]
fn it_does_not_expose_internal_error_sources() {
use std::error::Error as _;
let error = Error::from_kind(ErrorKind::Transport);
assert!(error.source().is_none());
assert!(!format!("{error:?}").contains("reqwest"));
}
}