diff --git a/src/api/client_server/errors/api_error.rs b/src/api/client_server/errors/api_error.rs new file mode 100644 index 0000000..33b9158 --- /dev/null +++ b/src/api/client_server/errors/api_error.rs @@ -0,0 +1,53 @@ +use axum::http::StatusCode; +use axum::response::IntoResponse; + +use super::registration_error::RegistrationError; + +macro_rules! map_err { + ($err:ident, $($type:path => $target:path),+) => { + $( + if $err.is::<$type>() { + return $target($err.downcast().unwrap()); + } + )* + } +} + +#[derive(Debug, thiserror::Error)] +pub enum ApiError { + #[error("Registration Error")] + RegistrationError(#[from] RegistrationError), + + #[error("Database Error")] + DBError(#[from] sqlx::Error), + + #[error("Generic Error")] + Generic(anyhow::Error), +} + +impl From for ApiError { + fn from(err: anyhow::Error) -> Self { + map_err!(err, + sqlx::Error => ApiError::DBError, + RegistrationError => ApiError::RegistrationError + ); + + ApiError::Generic(err) + } +} + +impl IntoResponse for ApiError { + fn into_response(self) -> axum::response::Response { + match self { + ApiError::RegistrationError(registration_error) => match registration_error { + RegistrationError::InvalidUserId => { + (StatusCode::OK, String::new()).into_response() + } + RegistrationError::MissingUserId => { + (StatusCode::OK, String::new()).into_response() + } + }, + _ => StatusCode::INTERNAL_SERVER_ERROR.into_response() + } + } +} diff --git a/src/api/client_server/errors/mod.rs b/src/api/client_server/errors/mod.rs new file mode 100644 index 0000000..5072c0c --- /dev/null +++ b/src/api/client_server/errors/mod.rs @@ -0,0 +1,2 @@ +pub mod api_error; +pub mod registration_error; diff --git a/src/api/client_server/errors/registration_error.rs b/src/api/client_server/errors/registration_error.rs new file mode 100644 index 0000000..5ca506f --- /dev/null +++ b/src/api/client_server/errors/registration_error.rs @@ -0,0 +1,7 @@ +#[derive(Debug, thiserror::Error)] +pub enum RegistrationError { + #[error("UserId is missing")] + MissingUserId, + #[error("UserId is invalid")] + InvalidUserId, +}