diff options
author | Vincent Ambo <mail@tazj.in> | 2019-02-26T21·21+0100 |
---|---|---|
committer | Vincent Ambo <mail@tazj.in> | 2019-02-26T21·21+0100 |
commit | e4e931661b23d1af41b97df3f17f937cd68cc77e (patch) | |
tree | bf93089359de3c29624e813334c758ad282140b5 /src/lib.rs | |
parent | 481825672ef5396c0c1e10adcad412a34b3488ef (diff) |
feat: Introduce `Response::error_for_status` method
This method makes it possible to let users map responses with unexpected HTTP statuses to custom errors while staying inside a chain of results.
Diffstat (limited to 'src/lib.rs')
-rw-r--r-- | src/lib.rs | 16 |
1 files changed, 15 insertions, 1 deletions
diff --git a/src/lib.rs b/src/lib.rs index 03baa127675a..a1f7e4de6432 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -133,7 +133,7 @@ enum Body<'a> { /// decoding a string via `Response::as_string` or to a /// `serde`-compatible type with `Response::as_json` (if the /// `json`-feature is enabled). -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub struct Response<T> { /// HTTP status code of the response. pub status: u32, @@ -431,6 +431,20 @@ impl <T> Response<T> { pub fn is_success(&self) -> bool { self.status >= 200 && self.status < 300 } + + /// Check whether a request succeeded and let users provide a + /// closure that creates an error from the request if it did not. + /// + /// This function exists for convenience to avoid having to write + /// repetitive `if !response.is_success() { ... }` blocks. + pub fn error_for_status<F, E>(self, closure: F) -> Result<Self, E> + where F: FnOnce(Self) -> E { + if !self.is_success() { + return Err(closure(self)) + } + + Ok(self) + } } impl Response<Vec<u8>> { |