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 all 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
51 changes: 51 additions & 0 deletions src/error.rs
Expand Up @@ -40,6 +40,30 @@ 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 {
self.get_ref().is::<T>()
}

/// Return a reference to the lower level, inner error.
pub fn get_ref(&self) -> &(error::Error + 'static) {
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 +80,13 @@ impl error::Error for Error {
HeaderValueShared(ref e) => e.description(),
}
}

// Return any available cause from the inner error. Note the inner error is
// not itself the cause.
#[allow(deprecated)]
fn cause(&self) -> Option<&error::Error> {
self.get_ref().cause()
}
}

impl From<status::InvalidStatusCode> for Error {
Expand Down Expand Up @@ -142,3 +173,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.get_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!");
}
}
}