From 9c139d6007a9993f0087b8a88fb198de41e9b55c Mon Sep 17 00:00:00 2001 From: GW_MC <72297530+GWMCwing@users.noreply.github.com> Date: Sun, 7 Dec 2025 14:40:11 +0800 Subject: [PATCH] refactor: replace IntoServiceError trait with direct ServiceError conversions --- apps/api/src/errors/service_error.rs | 28 ++++++++++++++++++---------- apps/api/src/services/settings.rs | 18 +++++++++--------- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/apps/api/src/errors/service_error.rs b/apps/api/src/errors/service_error.rs index 20a5835..e5d6b47 100644 --- a/apps/api/src/errors/service_error.rs +++ b/apps/api/src/errors/service_error.rs @@ -1,15 +1,23 @@ -pub type ServiceError = Box; +use sea_orm::DbErr; -#[allow(dead_code)] // TODO: remove when used -pub trait IntoServiceError { - fn into_service_error(self) -> ServiceError; +pub enum ServiceError { + NotFound(String), + DatabaseError(String), + Unauthorized(String), + InternalError(String), } -impl IntoServiceError for T -where - T: std::error::Error + Send + Sync + 'static, -{ - fn into_service_error(self) -> ServiceError { - Box::new(self) +impl From> for ServiceError { + fn from(err: Box) -> Self { + ServiceError::InternalError(err.to_string()) + } +} + +impl From for ServiceError { + fn from(err: DbErr) -> Self { + match err { + DbErr::RecordNotFound(msg) => ServiceError::NotFound(msg), + _ => ServiceError::DatabaseError(err.to_string()), + } } } diff --git a/apps/api/src/services/settings.rs b/apps/api/src/services/settings.rs index 847db61..20df281 100644 --- a/apps/api/src/services/settings.rs +++ b/apps/api/src/services/settings.rs @@ -7,7 +7,7 @@ use sea_orm::{ IntoActiveModel, QueryFilter, }; -use crate::errors::service_error::{IntoServiceError, ServiceError}; +use crate::errors::service_error::ServiceError; #[async_trait::async_trait] pub trait SettingsStore: Send + Sync { @@ -37,11 +37,11 @@ impl SettingsStore for SettingsService { .await; match setting { - Err(err) => Err(err.into_service_error()), - Ok(None) => Err( - DbErr::RecordNotFound(format!("Setting with key '{}' not found", key)) - .into_service_error(), - ), + Err(err) => Err(ServiceError::from(err)), + Ok(None) => Err(ServiceError::from(DbErr::RecordNotFound(format!( + "Setting with key '{}' not found", + key + )))), Ok(Some(record)) => Ok(record.value), } } @@ -62,7 +62,7 @@ impl SettingsStore for SettingsService { new_record .insert(&*self.connection) .await - .map_err(|err| err.into_service_error()) + .map_err(ServiceError::from) }; match existing { @@ -71,7 +71,7 @@ impl SettingsStore for SettingsService { handle_not_found(key.to_string(), value).await?; } _ => { - return Err(Box::new(err)); + return Err(ServiceError::from(err)); } }, Ok(None) => { @@ -83,7 +83,7 @@ impl SettingsStore for SettingsService { .into_active_model() .update(&*self.connection) .await - .map_err(|err| err.into_service_error())?; + .map_err(ServiceError::from)?; } }