diff --git a/src/async_impl/response.rs b/src/async_impl/response.rs index e3b2cec..e727eb8 100644 --- a/src/async_impl/response.rs +++ b/src/async_impl/response.rs @@ -167,6 +167,38 @@ impl Response { Ok(self) } } + + /// Turn a reference to a response into an error if the server returned an error. + /// + /// # Example + /// + /// ``` + /// # use reqwest::async::Response; + /// fn on_response(res: &Response) { + /// match res.error_for_status_ref() { + /// Ok(_res) => (), + /// Err(err) => { + /// // asserting a 400 as an example + /// // it could be any status between 400...599 + /// assert_eq!( + /// err.status(), + /// Some(reqwest::StatusCode::BAD_REQUEST) + /// ); + /// } + /// } + /// } + /// # fn main() {} + /// ``` + #[inline] + pub fn error_for_status_ref(&self) -> ::Result<&Self> { + if self.status.is_client_error() { + Err(::error::client_error(*self.url.clone(), self.status)) + } else if self.status.is_server_error() { + Err(::error::server_error(*self.url.clone(), self.status)) + } else { + Ok(self) + } + } } impl fmt::Debug for Response { diff --git a/src/response.rs b/src/response.rs index 57e9087..e2d7e79 100644 --- a/src/response.rs +++ b/src/response.rs @@ -329,6 +329,27 @@ impl Response { } }) } + + /// Turn a reference to a response into an error if the server returned an error. + /// + /// # Example + /// + /// ```rust,no_run + /// # extern crate reqwest; + /// # fn run() -> Result<(), Box<::std::error::Error>> { + /// let res = reqwest::get("http://httpbin.org/status/400")?; + /// let res = res.error_for_status_ref(); + /// if let Err(err) = res { + /// assert_eq!(err.status(), Some(reqwest::StatusCode::BAD_REQUEST)); + /// } + /// # Ok(()) + /// # } + /// # fn main() {} + /// ``` + #[inline] + pub fn error_for_status_ref(&self) -> ::Result<&Self> { + self.inner.error_for_status_ref().and_then(|_| Ok(self)) + } } impl Read for Response {