From 2b53b9ff7cee6a8442f406cb6fe3fcdd9c4e8909 Mon Sep 17 00:00:00 2001 From: Tolmachev Igor Date: Mon, 15 Sep 2025 02:06:52 +0300 Subject: Replace the error struct with an enum --- src/response/error.rs | 48 +++++++++++++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 21 deletions(-) (limited to 'src/response/error.rs') diff --git a/src/response/error.rs b/src/response/error.rs index c48489e..fb6a2fa 100644 --- a/src/response/error.rs +++ b/src/response/error.rs @@ -8,34 +8,34 @@ use utoipa::ToSchema; use crate::ApiError; #[derive(Serialize, ToSchema)] -enum ErrorStatus { +#[serde(tag = "status")] +pub enum ErrorResponse { #[serde(rename = "fail")] - Fail, + Fail { + #[schema(examples("SomeErrorKind", "NotAuthorized", "Database"))] + kind: String, + #[schema(examples("some error text"))] + message: String, + }, #[serde(rename = "error")] - Error, -} - -#[derive(Serialize, ToSchema)] -pub struct ErrorResponse { - status: ErrorStatus, - #[schema(examples("SomeErrorKind", "NotAuthorized", "Database"))] - kind: String, - #[schema(examples("some error text"))] - message: String, + Error { + #[schema(examples("SomeErrorKind", "NotAuthorized", "Database"))] + kind: String, + #[schema(examples("some error text"))] + message: String, + }, } impl ErrorResponse { pub fn fail(kind: impl Into, message: impl Into) -> Self { - Self { - status: ErrorStatus::Fail, + Self::Fail { kind: kind.into(), message: message.into(), } } pub fn error(kind: impl Into, message: impl Into) -> Self { - Self { - status: ErrorStatus::Error, + Self::Error { kind: kind.into(), message: message.into(), } @@ -45,9 +45,9 @@ impl ErrorResponse { impl IntoResponse for ErrorResponse { fn into_response(self) -> Response { ( - match self.status { - ErrorStatus::Fail => StatusCode::BAD_REQUEST, - ErrorStatus::Error => StatusCode::INTERNAL_SERVER_ERROR, + match self { + Self::Fail { .. } => StatusCode::BAD_REQUEST, + Self::Error { .. } => StatusCode::INTERNAL_SERVER_ERROR, }, axum::Json(self), ) @@ -61,8 +61,14 @@ where { fn from(value: T) -> Self { match value.into() { - ApiError::Client(e) => Self::fail(e.kind(), e.into_message()), - ApiError::Server(e) => Self::error(e.kind(), e.into_message()), + ApiError::Client(e) => Self::Fail { + kind: e.kind(), + message: e.into_message(), + }, + ApiError::Server(e) => Self::Error { + kind: e.kind(), + message: e.into_message(), + }, } } } -- cgit v1.2.3