From 3353eea1a031ad5f6a51d90b7ebd39958b837e50 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Mon, 31 Jul 2023 12:00:12 +0200 Subject: [PATCH] Generalize `RedisUnwrapOr500` trait to `UnwrapOr500` --- todored/src/routes/root.rs | 4 ++-- todored/src/utils.rs | 34 +++++++++++++++++++++++----------- 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/todored/src/routes/root.rs b/todored/src/routes/root.rs index 232341e..cc9aa65 100644 --- a/todored/src/routes/root.rs +++ b/todored/src/routes/root.rs @@ -1,7 +1,7 @@ use axum::{Extension, Json}; use axum::http::StatusCode; -use crate::utils::{RedisConnectOr500, RedisUnwrapOr500, Result}; +use crate::utils::{RedisConnectOr500, UnwrapOr500, Result}; const MAJOR: u32 = pkg_version::pkg_version_major!(); const MINOR: u32 = pkg_version::pkg_version_minor!(); @@ -24,7 +24,7 @@ pub async fn healthcheck( log::trace!("Sending PING..."); let response = redis::cmd("PING") .query_async::(&mut rconn).await - .unwrap_or_500_and_log()?; + .expect_or_500_and_log("Failed to PING Redis")?; log::trace!("Sent PING and received: {:?}", response); diff --git a/todored/src/utils.rs b/todored/src/utils.rs index 21f29d3..8401405 100644 --- a/todored/src/utils.rs +++ b/todored/src/utils.rs @@ -1,20 +1,32 @@ +use std::fmt::Debug; use async_trait::async_trait; use axum::http::StatusCode; pub type Result = std::result::Result; -pub(crate) trait RedisUnwrapOr500 { - fn unwrap_or_500_and_log(self) -> Result; +pub(crate) trait UnwrapOr500 { + fn unwrap_or_500(self) -> Result; + fn unwrap_or_500_and_log(self) -> Result where E: Debug; + fn expect_or_500_and_log(self, text: &str) -> Result where E: Debug; } -impl RedisUnwrapOr500 for redis::RedisResult { - fn unwrap_or_500_and_log(self) -> Result { - self - .map_err(|e| { - log::error!("{e:#?}"); - e - }) - .or(Err(StatusCode::INTERNAL_SERVER_ERROR)) +impl UnwrapOr500 for std::result::Result { + fn unwrap_or_500(self) -> Result { + self.or(Err(StatusCode::INTERNAL_SERVER_ERROR)) + } + + fn unwrap_or_500_and_log(self) -> Result where E: Debug { + self.map_err(|e| { + log::error!("{e:?}"); + e + }).unwrap_or_500() + } + + fn expect_or_500_and_log(self, text: &str) -> Result where E: Debug { + self.map_err(|e| { + log::error!("{text}: {e:?}"); + e + }).unwrap_or_500() } } @@ -29,7 +41,7 @@ impl RedisConnectOr500 for redis::Client { log::trace!("Connecting to Redis..."); let rconn = self.get_async_connection().await - .unwrap_or_500_and_log()?; + .expect_or_500_and_log("Failed to connect to Redis")?; log::trace!("Connection successful!"); Ok(rconn)