From 15338e77b789da999cb4cdc829127f8dea8854d9 Mon Sep 17 00:00:00 2001 From: Aleksander <170264518+t-aleksander@users.noreply.github.com> Date: Tue, 6 Aug 2024 09:21:26 +0200 Subject: [PATCH] fix: fix error codes and messages (#73) --- src/error.rs | 16 ++++++++-------- src/handlers/mod.rs | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/error.rs b/src/error.rs index b232fed..d5eec03 100644 --- a/src/error.rs +++ b/src/error.rs @@ -10,8 +10,8 @@ use tonic::{Code, Status}; #[derive(thiserror::Error, Debug)] pub enum ApiError { - #[error("Unauthorized")] - Unauthorized, + #[error("Unauthorized: {0}")] + Unauthorized(String), #[error("Unexpected error: {0}")] Unexpected(String), #[error(transparent)] @@ -22,17 +22,17 @@ pub enum ApiError { CoreTimeout, #[error("Invalid core gRPC response type received")] InvalidResponseType, - #[error("Permission denied")] - PermissionDenied, + #[error("Permission denied: {0}")] + PermissionDenied(String), } impl IntoResponse for ApiError { fn into_response(self) -> Response { error!("{}", self); let (status, error_message) = match self { - Self::Unauthorized => (StatusCode::UNAUTHORIZED, self.to_string()), + Self::Unauthorized(msg) => (StatusCode::UNAUTHORIZED, msg), Self::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg), - Self::PermissionDenied => (StatusCode::FORBIDDEN, self.to_string()), + Self::PermissionDenied(msg) => (StatusCode::FORBIDDEN, msg), _ => ( StatusCode::INTERNAL_SERVER_ERROR, "Internal server error".to_string(), @@ -52,9 +52,9 @@ impl From for ApiError { // convert to tonic::Status first let status = Status::new(Code::from(core_error.status_code), core_error.message); match status.code() { - Code::Unauthenticated => ApiError::Unauthorized, + Code::Unauthenticated => ApiError::Unauthorized(status.message().to_string()), Code::InvalidArgument => ApiError::BadRequest(status.message().to_string()), - Code::PermissionDenied => ApiError::PermissionDenied, + Code::PermissionDenied => ApiError::PermissionDenied(status.message().to_string()), _ => ApiError::Unexpected(status.to_string()), } } diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs index b4c70b9..2d1c62f 100644 --- a/src/handlers/mod.rs +++ b/src/handlers/mod.rs @@ -49,7 +49,7 @@ async fn get_core_response(rx: Receiver) -> Result { if let Ok(core_response) = timeout(Duration::from_secs(CORE_RESPONSE_TIMEOUT), rx).await { debug!("Got gRPC response from Defguard core: {core_response:?}"); if let Ok(Payload::CoreError(core_error)) = core_response { - return Err(ApiError::BadRequest(format!("{}", core_error.message))); + return Err(core_error.into()); }; core_response .map_err(|err| ApiError::Unexpected(format!("Failed to receive core response: {err}")))