From 955598dce9aeb5626654c72b0ef94850123fa8ac Mon Sep 17 00:00:00 2001 From: Tolmachev Igor Date: Sun, 14 Sep 2025 23:27:25 +0300 Subject: Add openapi specs and docs --- src/response/error.rs | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/response/error.rs (limited to 'src/response/error.rs') diff --git a/src/response/error.rs b/src/response/error.rs new file mode 100644 index 0000000..db39da8 --- /dev/null +++ b/src/response/error.rs @@ -0,0 +1,69 @@ +use axum::{ + http::StatusCode, + response::{IntoResponse, Response}, +}; +use serde::Serialize; +use utoipa::ToSchema; + +use crate::ApiError; + +#[derive(Serialize, ToSchema)] +#[schema(examples("fail or error"))] +enum ErrorStatus { + #[serde(rename = "fail")] + Fail, + #[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, +} + +impl ErrorResponse { + pub fn fail(kind: impl Into, message: impl Into) -> Self { + Self { + status: ErrorStatus::Fail, + kind: kind.into(), + message: message.into(), + } + } + + pub fn error(kind: impl Into, message: impl Into) -> Self { + Self { + status: ErrorStatus::Error, + kind: kind.into(), + message: message.into(), + } + } +} + +impl IntoResponse for ErrorResponse { + fn into_response(self) -> Response { + ( + match self.status { + ErrorStatus::Fail => StatusCode::BAD_REQUEST, + ErrorStatus::Error => StatusCode::INTERNAL_SERVER_ERROR, + }, + axum::Json(self), + ) + .into_response() + } +} + +impl From for ErrorResponse +where + T: Into, +{ + fn from(value: T) -> Self { + match value.into() { + ApiError::Client(e) => Self::fail(e.kind(), e.into_message()), + ApiError::Server(e) => Self::fail(e.kind(), e.into_message()), + } + } +} -- cgit v1.2.3