Skip to content

Commit

Permalink
fix: fix error codes and messages (#73)
Browse files Browse the repository at this point in the history
  • Loading branch information
t-aleksander authored Aug 6, 2024
1 parent fb5241d commit 15338e7
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 9 deletions.
16 changes: 8 additions & 8 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -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(),
Expand All @@ -52,9 +52,9 @@ impl From<CoreError> 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()),
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ async fn get_core_response(rx: Receiver<Payload>) -> Result<Payload, ApiError> {
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}")))
Expand Down

0 comments on commit 15338e7

Please sign in to comment.