add is_not_found functor to error; tweak status code matcher

Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
Jason Volk 2024-09-12 00:01:25 +00:00 committed by strawberry
parent a5822ebc27
commit f7ce4db0b0
3 changed files with 30 additions and 7 deletions

View file

@ -141,19 +141,22 @@ impl Error {
use ruma::api::client::error::ErrorKind::Unknown; use ruma::api::client::error::ErrorKind::Unknown;
match self { 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(), Self::BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(),
_ => Unknown, _ => Unknown,
} }
} }
pub fn status_code(&self) -> http::StatusCode { pub fn status_code(&self) -> http::StatusCode {
use http::StatusCode;
match self { match self {
Self::Federation(_, ref error) | Self::Ruma(ref error) => error.status_code, Self::Federation(_, error) | Self::Ruma(error) => error.status_code,
Self::Request(ref kind, _, code) => response::status_code(kind, *code), Self::Request(kind, _, code) => response::status_code(kind, *code),
Self::BadRequest(ref kind, ..) => response::bad_request_code(kind), Self::BadRequest(kind, ..) => response::bad_request_code(kind),
Self::Conflict(_) => http::StatusCode::CONFLICT, Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
_ => http::StatusCode::INTERNAL_SERVER_ERROR, Self::Conflict(_) => StatusCode::CONFLICT,
_ => StatusCode::INTERNAL_SERVER_ERROR,
} }
} }
} }
@ -176,3 +179,7 @@ impl From<Infallible> for Error {
pub fn infallible(_e: &Infallible) { pub fn infallible(_e: &Infallible) {
panic!("infallible error should never exist"); panic!("infallible error should never exist");
} }
#[inline]
#[must_use]
pub fn is_not_found(e: &Error) -> bool { e.status_code() == http::StatusCode::NOT_FOUND }

View file

@ -2,7 +2,11 @@ mod debug_inspect;
mod log_debug_err; mod log_debug_err;
mod log_err; mod log_err;
mod map_expect; 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<T = (), E = crate::Error> = std::result::Result<T, E>; pub type Result<T = (), E = crate::Error> = std::result::Result<T, E>;

View file

@ -0,0 +1,12 @@
use super::Result;
use crate::{error, Error};
pub trait NotFound<T> {
#[must_use]
fn is_not_found(&self) -> bool;
}
impl<T> NotFound<T> for Result<T, Error> {
#[inline]
fn is_not_found(&self) -> bool { self.as_ref().is_err_and(error::is_not_found) }
}