Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add http::Error::inner_ref and cause #303

Merged
merged 4 commits into from Apr 2, 2019
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
49 changes: 49 additions & 0 deletions src/error.rs
Expand Up @@ -40,6 +40,31 @@ impl fmt::Display for Error {
}
}

impl Error {
/// Return true if the underlying error has the same type as T.
pub fn is<T: error::Error + 'static>(&self) -> bool {
let ie = self.inner_ref();
ie.is::<T>()
}

/// Return a reference to the lower level, inner error.
pub fn inner_ref(&self) -> &(error::Error + 'static) {
dekellum marked this conversation as resolved.
Show resolved Hide resolved
use self::ErrorKind::*;

match self.inner {
StatusCode(ref e) => e,
Method(ref e) => e,
Uri(ref e) => e,
UriShared(ref e) => e,
UriParts(ref e) => e,
HeaderName(ref e) => e,
HeaderNameShared(ref e) => e,
HeaderValue(ref e) => e,
HeaderValueShared(ref e) => e,
}
}
}

impl error::Error for Error {
fn description(&self) -> &str {
use self::ErrorKind::*;
Expand All @@ -56,6 +81,10 @@ impl error::Error for Error {
HeaderValueShared(ref e) => e.description(),
}
}

fn cause(&self) -> Option<&error::Error> {
Some(self.inner_ref())
dekellum marked this conversation as resolved.
Show resolved Hide resolved
}
}

impl From<status::InvalidStatusCode> for Error {
Expand Down Expand Up @@ -142,3 +171,23 @@ impl error::Error for Never {
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn inner_error_is_invalid_status_code() {
if let Err(e) = status::StatusCode::from_u16(6666) {
let err: Error = e.into();
let ie = err.inner_ref();
assert!(!ie.is::<header::InvalidHeaderValue>());
assert!( ie.is::<status::InvalidStatusCode>());
ie.downcast_ref::<status::InvalidStatusCode>().unwrap();

assert!(!err.is::<header::InvalidHeaderValue>());
assert!( err.is::<status::InvalidStatusCode>());
} else {
panic!("Bad status allowed!");
}
}
}