diff --git a/crates/ruma-common/src/api/error.rs b/crates/ruma-common/src/api/error.rs index 41bb7788..fbaf3146 100644 --- a/crates/ruma-common/src/api/error.rs +++ b/crates/ruma-common/src/api/error.rs @@ -134,6 +134,30 @@ pub enum FromHttpResponseError { Server(ServerError), } +impl FromHttpResponseError { + /// Map `FromHttpResponseError` to `FromHttpResponseError` by applying a function to a + /// contained `Server` value, leaving a `Deserialization` value untouched. + pub fn map( + self, + f: impl FnOnce(ServerError) -> ServerError, + ) -> FromHttpResponseError { + match self { + Self::Deserialization(d) => FromHttpResponseError::Deserialization(d), + Self::Server(s) => FromHttpResponseError::Server(f(s)), + } + } +} + +impl FromHttpResponseError> { + /// Transpose `FromHttpResponseError>` to `Result, F>`. + pub fn transpose(self) -> Result, F> { + match self { + Self::Deserialization(d) => Ok(FromHttpResponseError::Deserialization(d)), + Self::Server(s) => s.transpose().map(FromHttpResponseError::Server), + } + } +} + impl fmt::Display for FromHttpResponseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { @@ -172,6 +196,28 @@ pub enum ServerError { Unknown(DeserializationError), } +impl ServerError { + /// Map `ServerError` to `ServerError` by applying a function to a contained `Known` + /// value, leaving an `Unknown` value untouched. + pub fn map(self, f: impl FnOnce(E) -> F) -> ServerError { + match self { + Self::Known(k) => ServerError::Known(f(k)), + Self::Unknown(u) => ServerError::Unknown(u), + } + } +} + +impl ServerError> { + /// Transpose `ServerError>` to `Result, F>`. + pub fn transpose(self) -> Result, F> { + match self { + Self::Known(Ok(k)) => Ok(ServerError::Known(k)), + Self::Known(Err(e)) => Err(e), + Self::Unknown(u) => Ok(ServerError::Unknown(u)), + } + } +} + impl fmt::Display for ServerError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self {