De-redundantize Error kinds. (#259)

Change "Bad" to "Invalid" in error names, mimicking io::Error::ErrorKind.

Change InvalidProxyCreds to ProxyUnauthorized.

Change DnsFailed to just Dns (the fact that there was a failure is implicit
in the fact that this was an error).
This commit is contained in:
Jacob Hoffman-Andrews
2020-12-05 12:05:29 -08:00
committed by GitHub
parent 57f251d766
commit 6c9378ce37
7 changed files with 27 additions and 30 deletions

View File

@@ -168,11 +168,11 @@ impl Error {
#[derive(Debug, PartialEq, Clone, Copy)] #[derive(Debug, PartialEq, Clone, Copy)]
pub enum ErrorKind { pub enum ErrorKind {
/// The url could not be understood. /// The url could not be understood.
BadUrl, InvalidUrl,
/// The url scheme could not be understood. /// The url scheme could not be understood.
UnknownScheme, UnknownScheme,
/// DNS lookup failed. /// DNS lookup failed.
DnsFailed, Dns,
/// Connection to server failed. /// Connection to server failed.
ConnectionFailed, ConnectionFailed,
/// Too many redirects. /// Too many redirects.
@@ -184,14 +184,12 @@ pub enum ErrorKind {
/// Some unspecified `std::io::Error`. /// Some unspecified `std::io::Error`.
Io, Io,
/// Proxy information was not properly formatted /// Proxy information was not properly formatted
BadProxy, InvalidProxyUrl,
/// Proxy credentials were not properly formatted
BadProxyCreds,
/// Proxy could not connect /// Proxy could not connect
ProxyConnect, ProxyConnect,
/// Incorrect credentials for proxy /// Incorrect credentials for proxy
InvalidProxyCreds, ProxyUnauthorized,
/// HTTP status code indicating an error (e.g. 4xx, 5xx). /// HTTP status code indicating an error (e.g. 4xx, 5xx)
/// Read the inner response body for details and to return /// Read the inner response body for details and to return
/// the connection to the pool. /// the connection to the pool.
HTTP, HTTP,
@@ -228,18 +226,17 @@ impl From<Transport> for Error {
impl fmt::Display for ErrorKind { impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
ErrorKind::BadUrl => write!(f, "Bad URL"), ErrorKind::InvalidUrl => write!(f, "Bad URL"),
ErrorKind::UnknownScheme => write!(f, "Unknown Scheme"), ErrorKind::UnknownScheme => write!(f, "Unknown Scheme"),
ErrorKind::DnsFailed => write!(f, "Dns Failed"), ErrorKind::Dns => write!(f, "Dns Failed"),
ErrorKind::ConnectionFailed => write!(f, "Connection Failed"), ErrorKind::ConnectionFailed => write!(f, "Connection Failed"),
ErrorKind::TooManyRedirects => write!(f, "Too Many Redirects"), ErrorKind::TooManyRedirects => write!(f, "Too Many Redirects"),
ErrorKind::BadStatus => write!(f, "Bad Status"), ErrorKind::BadStatus => write!(f, "Bad Status"),
ErrorKind::BadHeader => write!(f, "Bad Header"), ErrorKind::BadHeader => write!(f, "Bad Header"),
ErrorKind::Io => write!(f, "Network Error"), ErrorKind::Io => write!(f, "Network Error"),
ErrorKind::BadProxy => write!(f, "Malformed proxy"), ErrorKind::InvalidProxyUrl => write!(f, "Malformed proxy"),
ErrorKind::BadProxyCreds => write!(f, "Failed to parse proxy credentials"),
ErrorKind::ProxyConnect => write!(f, "Proxy failed to connect"), ErrorKind::ProxyConnect => write!(f, "Proxy failed to connect"),
ErrorKind::InvalidProxyCreds => write!(f, "Provided proxy credentials are incorrect"), ErrorKind::ProxyUnauthorized => write!(f, "Provided proxy credentials are incorrect"),
ErrorKind::HTTP => write!(f, "HTTP status error"), ErrorKind::HTTP => write!(f, "HTTP status error"),
} }
} }
@@ -282,6 +279,6 @@ fn connection_closed() {
fn error_is_send_and_sync() { fn error_is_send_and_sync() {
fn takes_send(_: impl Send) {} fn takes_send(_: impl Send) {}
fn takes_sync(_: impl Sync) {} fn takes_sync(_: impl Sync) {}
takes_send(crate::error::ErrorKind::BadUrl.new()); takes_send(crate::error::ErrorKind::InvalidUrl.new());
takes_sync(crate::error::ErrorKind::BadUrl.new()); takes_sync(crate::error::ErrorKind::InvalidUrl.new());
} }

View File

@@ -369,7 +369,7 @@ mod tests {
#[cfg(feature = "tls")] #[cfg(feature = "tls")]
fn connect_https_invalid_name() { fn connect_https_invalid_name() {
let result = get("https://example.com{REQUEST_URI}/").call(); let result = get("https://example.com{REQUEST_URI}/").call();
let e = ErrorKind::DnsFailed; let e = ErrorKind::Dns;
assert_eq!(result.unwrap_err().kind(), e); assert_eq!(result.unwrap_err().kind(), e);
} }
} }

View File

@@ -30,7 +30,7 @@ impl Proxy {
.into_iter(); .into_iter();
if parts.len() != 2 { if parts.len() != 2 {
Err(ErrorKind::BadProxyCreds.new()) Err(ErrorKind::InvalidProxyUrl.new())
} else { } else {
Ok(( Ok((
parts.next().map(String::from), parts.next().map(String::from),
@@ -46,14 +46,14 @@ impl Proxy {
match host { match host {
Some(host) => { Some(host) => {
let mut parts = host.as_ref().split(':').collect::<Vec<&str>>().into_iter(); let mut parts = host.as_ref().split(':').collect::<Vec<&str>>().into_iter();
let host = parts.next().ok_or(ErrorKind::BadProxy.new())?; let host = parts.next().ok_or(ErrorKind::InvalidProxyUrl.new())?;
let port = parts.next(); let port = parts.next();
Ok(( Ok((
String::from(host), String::from(host),
port.and_then(|port| port.parse::<u32>().ok()), port.and_then(|port| port.parse::<u32>().ok()),
)) ))
} }
None => Err(ErrorKind::BadProxy.new()), None => Err(ErrorKind::InvalidProxyUrl.new()),
} }
} }
@@ -84,7 +84,7 @@ impl Proxy {
Some("http") => Proto::HTTPConnect, Some("http") => Proto::HTTPConnect,
Some("socks") => Proto::SOCKS5, Some("socks") => Proto::SOCKS5,
Some("socks5") => Proto::SOCKS5, Some("socks5") => Proto::SOCKS5,
_ => return Err(ErrorKind::BadProxy.new()), _ => return Err(ErrorKind::InvalidProxyUrl.new()),
} }
} else { } else {
Proto::HTTPConnect Proto::HTTPConnect
@@ -92,7 +92,7 @@ impl Proxy {
let remaining_parts = proxy_parts.next(); let remaining_parts = proxy_parts.next();
if remaining_parts == None { if remaining_parts == None {
return Err(ErrorKind::BadProxy.new()); return Err(ErrorKind::InvalidProxyUrl.new());
} }
let mut creds_server_port_parts = remaining_parts let mut creds_server_port_parts = remaining_parts
@@ -159,12 +159,12 @@ Proxy-Connection: Keep-Alive\r\n\
let status_code = top_line let status_code = top_line
.split_whitespace() .split_whitespace()
.nth(1) .nth(1)
.ok_or(ErrorKind::BadProxy.new())?; .ok_or(ErrorKind::ProxyConnect.new())?;
match status_code { match status_code {
"200" => Ok(()), "200" => Ok(()),
"401" | "407" => Err(ErrorKind::InvalidProxyCreds.new()), "401" | "407" => Err(ErrorKind::ProxyUnauthorized.new()),
_ => Err(ErrorKind::BadProxy.new()), _ => Err(ErrorKind::ProxyConnect.new()),
} }
} }
} }

View File

@@ -108,7 +108,7 @@ impl Request {
let mut url: Url = match self.url.clone() { let mut url: Url = match self.url.clone() {
Urlish::Url(u) => u, Urlish::Url(u) => u,
Urlish::Str(s) => s.parse().map_err(|e: url::ParseError| { Urlish::Str(s) => s.parse().map_err(|e: url::ParseError| {
ErrorKind::BadUrl ErrorKind::InvalidUrl
.msg(&format!("failed to parse URL '{}'", self.url)) .msg(&format!("failed to parse URL '{}'", self.url))
.src(e) .src(e)
})?, })?,

View File

@@ -341,7 +341,7 @@ pub(crate) fn connect_https(unit: &Unit, hostname: &str) -> Result<Stream, Error
let port = unit.url.port().unwrap_or(443); let port = unit.url.port().unwrap_or(443);
let sni = webpki::DNSNameRef::try_from_ascii_str(hostname) let sni = webpki::DNSNameRef::try_from_ascii_str(hostname)
.map_err(|err| ErrorKind::DnsFailed.new().src(err))?; .map_err(|err| ErrorKind::Dns.new().src(err))?;
let tls_conf: &Arc<rustls::ClientConfig> = unit let tls_conf: &Arc<rustls::ClientConfig> = unit
.agent .agent
.config .config
@@ -375,10 +375,10 @@ pub(crate) fn connect_host(unit: &Unit, hostname: &str, port: u16) -> Result<Tcp
let sock_addrs = unit let sock_addrs = unit
.resolver() .resolver()
.resolve(&netloc) .resolve(&netloc)
.map_err(|e| ErrorKind::DnsFailed.new().src(e))?; .map_err(|e| ErrorKind::Dns.new().src(e))?;
if sock_addrs.is_empty() { if sock_addrs.is_empty() {
return Err(ErrorKind::DnsFailed.msg(&format!("No ip address for {}", hostname))); return Err(ErrorKind::Dns.msg(&format!("No ip address for {}", hostname)));
} }
let proto = if let Some(ref proxy) = proxy { let proto = if let Some(ref proxy) = proxy {

View File

@@ -106,7 +106,7 @@ fn redirect_host() {
let url = format!("http://localhost:{}/", srv.port); let url = format!("http://localhost:{}/", srv.port);
let result = crate::Agent::new().get(&url).call(); let result = crate::Agent::new().get(&url).call();
assert!( assert!(
matches!(result, Err(ref e) if e.kind() == ErrorKind::DnsFailed), matches!(result, Err(ref e) if e.kind() == ErrorKind::Dns),
"expected Err(DnsFailed), got: {:?}", "expected Err(DnsFailed), got: {:?}",
result result
); );

View File

@@ -172,7 +172,7 @@ pub(crate) fn connect(
let host = unit let host = unit
.url .url
.host_str() .host_str()
.ok_or(ErrorKind::BadUrl.msg("no host in URL"))?; .ok_or(ErrorKind::InvalidUrl.msg("no host in URL"))?;
let url = &unit.url; let url = &unit.url;
let method = &unit.method; let method = &unit.method;
// open socket // open socket
@@ -241,7 +241,7 @@ pub(crate) fn connect(
if let Some(location) = location { if let Some(location) = location {
// join location header to current url in case it it relative // join location header to current url in case it it relative
let new_url = url.join(location).map_err(|e| { let new_url = url.join(location).map_err(|e| {
ErrorKind::BadUrl ErrorKind::InvalidUrl
.msg(&format!("Bad redirection: {}", location)) .msg(&format!("Bad redirection: {}", location))
.src(e) .src(e)
})?; })?;