From 39b1d9107d870b6ebb8173efbfa7cd8b57547285 Mon Sep 17 00:00:00 2001 From: Adam Leventhal Date: Wed, 23 Feb 2022 21:07:30 -0800 Subject: [PATCH] add helper functions to Error and ResponseValue (#28) --- docs/generated_methods.md | 2 +- progenitor-client/src/lib.rs | 40 +++++++++++++++++++++++++++++++++--- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/docs/generated_methods.md b/docs/generated_methods.md index fb2bc4d..9e66c65 100644 --- a/docs/generated_methods.md +++ b/docs/generated_methods.md @@ -23,7 +23,7 @@ impl Client { ``` For more info on the `ResponseValue` and `Error` types, see -[progenitor_client](./progenitor_client). +[progenitor_client](./progenitor-client.md). Note that methods are `async` so must be `await`ed to get the response. diff --git a/progenitor-client/src/lib.rs b/progenitor-client/src/lib.rs index 4f1c055..d4b649b 100644 --- a/progenitor-client/src/lib.rs +++ b/progenitor-client/src/lib.rs @@ -56,9 +56,10 @@ impl ResponseValue { } /// Get the status from this response. - pub fn status(&self) -> &reqwest::StatusCode { - &self.status + pub fn status(&self) -> reqwest::StatusCode { + self.status } + /// Get the headers from this response. pub fn headers(&self) -> &reqwest::header::HeaderMap { &self.headers @@ -112,7 +113,7 @@ impl std::fmt::Debug for ResponseValue { /// or an enum if there are multiple valid error types. It can be the unit type /// if there are no structured returns expected. #[derive(Debug)] -pub enum Error { +pub enum Error { /// A server error either with the data, or with the connection. CommunicationError(reqwest::Error), @@ -128,6 +129,39 @@ pub enum Error { UnexpectedResponse(reqwest::Response), } +impl Error { + /// Returns the status code, if the error was generated from a response. + pub fn status(&self) -> Option { + match self { + Error::CommunicationError(e) => e.status(), + Error::ErrorResponse(rv) => Some(rv.status()), + Error::InvalidResponsePayload(e) => e.status(), + Error::UnexpectedResponse(r) => Some(r.status()), + } + } + + /// Convert this error into one without a typed body for unified error + /// handling with APIs that distinguish various error response bodies. + pub fn into_untyped(self) -> Error { + match self { + Error::CommunicationError(e) => Error::CommunicationError(e), + Error::ErrorResponse(ResponseValue { + inner: _, + status, + headers, + }) => Error::ErrorResponse(ResponseValue { + inner: (), + status, + headers, + }), + Error::InvalidResponsePayload(e) => { + Error::InvalidResponsePayload(e) + } + Error::UnexpectedResponse(r) => Error::UnexpectedResponse(r), + } + } +} + impl From for Error { fn from(e: reqwest::Error) -> Self { Self::CommunicationError(e)