From b1f40b776d64658b6dae621911441ceaf1ff8607 Mon Sep 17 00:00:00 2001 From: Sean McArthur Date: Fri, 12 May 2017 22:03:24 -0700 Subject: [PATCH] add Error::get_ref method with 'static bound --- src/error.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/error.rs b/src/error.rs index 46a2007..bda4c02 100644 --- a/src/error.rs +++ b/src/error.rs @@ -20,6 +20,21 @@ impl Error { self.url.as_ref() } + /// Returns a reference to the internal error, if available. + /// + /// The `'static` bounds allows using `downcast_ref` to check the + /// details of the error. + #[inline] + pub fn get_ref(&self) -> Option<&(StdError + 'static)> { + match self.kind { + Kind::Http(ref e) => Some(e), + Kind::UrlEncoded(ref e) => Some(e), + Kind::Json(ref e) => Some(e), + Kind::TooManyRedirects | + Kind::RedirectLoop => None, + } + } + /// Returns true if the error is related to HTTP. #[inline] pub fn is_http(&self) -> bool { @@ -189,3 +204,15 @@ macro_rules! try_ { } ) } + +#[test] +fn test_error_get_ref_downcasts() { + let err: Error = from(::hyper::Error::Status); + let cause = err.get_ref().unwrap() + .downcast_ref::<::hyper::Error>().unwrap(); + + match cause { + &::hyper::Error::Status => (), + _ => panic!("unexpected downcast: {:?}", cause) + } +}