From f7ce4db0b00bc24be6c127895e16ba29a248c8a4 Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Thu, 12 Sep 2024 00:01:25 +0000 Subject: [PATCH] add is_not_found functor to error; tweak status code matcher Signed-off-by: Jason Volk --- src/core/error/mod.rs | 19 +++++++++++++------ src/core/result.rs | 6 +++++- src/core/result/not_found.rs | 12 ++++++++++++ 3 files changed, 30 insertions(+), 7 deletions(-) create mode 100644 src/core/result/not_found.rs diff --git a/src/core/error/mod.rs b/src/core/error/mod.rs index 92dbdfe3..48b9b58f 100644 --- a/src/core/error/mod.rs +++ b/src/core/error/mod.rs @@ -141,19 +141,22 @@ impl Error { use ruma::api::client::error::ErrorKind::Unknown; match self { - Self::Federation(_, error) => response::ruma_error_kind(error).clone(), + Self::Federation(_, error) | Self::Ruma(error) => response::ruma_error_kind(error).clone(), Self::BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(), _ => Unknown, } } pub fn status_code(&self) -> http::StatusCode { + use http::StatusCode; + match self { - Self::Federation(_, ref error) | Self::Ruma(ref error) => error.status_code, - Self::Request(ref kind, _, code) => response::status_code(kind, *code), - Self::BadRequest(ref kind, ..) => response::bad_request_code(kind), - Self::Conflict(_) => http::StatusCode::CONFLICT, - _ => http::StatusCode::INTERNAL_SERVER_ERROR, + Self::Federation(_, error) | Self::Ruma(error) => error.status_code, + Self::Request(kind, _, code) => response::status_code(kind, *code), + Self::BadRequest(kind, ..) => response::bad_request_code(kind), + Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), + Self::Conflict(_) => StatusCode::CONFLICT, + _ => StatusCode::INTERNAL_SERVER_ERROR, } } } @@ -176,3 +179,7 @@ impl From for Error { pub fn infallible(_e: &Infallible) { panic!("infallible error should never exist"); } + +#[inline] +#[must_use] +pub fn is_not_found(e: &Error) -> bool { e.status_code() == http::StatusCode::NOT_FOUND } diff --git a/src/core/result.rs b/src/core/result.rs index c3eaf95b..41d1d66c 100644 --- a/src/core/result.rs +++ b/src/core/result.rs @@ -2,7 +2,11 @@ mod debug_inspect; mod log_debug_err; mod log_err; mod map_expect; +mod not_found; -pub use self::{debug_inspect::DebugInspect, log_debug_err::LogDebugErr, log_err::LogErr, map_expect::MapExpect}; +pub use self::{ + debug_inspect::DebugInspect, log_debug_err::LogDebugErr, log_err::LogErr, map_expect::MapExpect, + not_found::NotFound, +}; pub type Result = std::result::Result; diff --git a/src/core/result/not_found.rs b/src/core/result/not_found.rs new file mode 100644 index 00000000..69ce821b --- /dev/null +++ b/src/core/result/not_found.rs @@ -0,0 +1,12 @@ +use super::Result; +use crate::{error, Error}; + +pub trait NotFound { + #[must_use] + fn is_not_found(&self) -> bool; +} + +impl NotFound for Result { + #[inline] + fn is_not_found(&self) -> bool { self.as_ref().is_err_and(error::is_not_found) } +}