diff options
| author | Tolmachev Igor <me@igorek.dev> | 2025-09-14 23:27:25 +0300 |
|---|---|---|
| committer | Tolmachev Igor <me@igorek.dev> | 2025-09-14 23:27:25 +0300 |
| commit | 955598dce9aeb5626654c72b0ef94850123fa8ac (patch) | |
| tree | 4fb161c2e67fdc161ebbca5ced271b6e7724dc30 /src/response/error.rs | |
| parent | 39bf8397949ea2738ac3dfc934fcc3f07a6b0b66 (diff) | |
| download | queue_server-955598dce9aeb5626654c72b0ef94850123fa8ac.tar.gz queue_server-955598dce9aeb5626654c72b0ef94850123fa8ac.zip | |
Add openapi specs and docs
Diffstat (limited to 'src/response/error.rs')
| -rw-r--r-- | src/response/error.rs | 69 |
1 files changed, 69 insertions, 0 deletions
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 @@ | |||
| 1 | use axum::{ | ||
| 2 | http::StatusCode, | ||
| 3 | response::{IntoResponse, Response}, | ||
| 4 | }; | ||
| 5 | use serde::Serialize; | ||
| 6 | use utoipa::ToSchema; | ||
| 7 | |||
| 8 | use crate::ApiError; | ||
| 9 | |||
| 10 | #[derive(Serialize, ToSchema)] | ||
| 11 | #[schema(examples("fail or error"))] | ||
| 12 | enum ErrorStatus { | ||
| 13 | #[serde(rename = "fail")] | ||
| 14 | Fail, | ||
| 15 | #[serde(rename = "error")] | ||
| 16 | Error, | ||
| 17 | } | ||
| 18 | |||
| 19 | #[derive(Serialize, ToSchema)] | ||
| 20 | pub struct ErrorResponse { | ||
| 21 | status: ErrorStatus, | ||
| 22 | #[schema(examples("SomeErrorKind", "NotAuthorized", "Database"))] | ||
| 23 | kind: String, | ||
| 24 | #[schema(examples("some error text"))] | ||
| 25 | message: String, | ||
| 26 | } | ||
| 27 | |||
| 28 | impl ErrorResponse { | ||
| 29 | pub fn fail(kind: impl Into<String>, message: impl Into<String>) -> Self { | ||
| 30 | Self { | ||
| 31 | status: ErrorStatus::Fail, | ||
| 32 | kind: kind.into(), | ||
| 33 | message: message.into(), | ||
| 34 | } | ||
| 35 | } | ||
| 36 | |||
| 37 | pub fn error(kind: impl Into<String>, message: impl Into<String>) -> Self { | ||
| 38 | Self { | ||
| 39 | status: ErrorStatus::Error, | ||
| 40 | kind: kind.into(), | ||
| 41 | message: message.into(), | ||
| 42 | } | ||
| 43 | } | ||
| 44 | } | ||
| 45 | |||
| 46 | impl IntoResponse for ErrorResponse { | ||
| 47 | fn into_response(self) -> Response { | ||
| 48 | ( | ||
| 49 | match self.status { | ||
| 50 | ErrorStatus::Fail => StatusCode::BAD_REQUEST, | ||
| 51 | ErrorStatus::Error => StatusCode::INTERNAL_SERVER_ERROR, | ||
| 52 | }, | ||
| 53 | axum::Json(self), | ||
| 54 | ) | ||
| 55 | .into_response() | ||
| 56 | } | ||
| 57 | } | ||
| 58 | |||
| 59 | impl<T> From<T> for ErrorResponse | ||
| 60 | where | ||
| 61 | T: Into<ApiError>, | ||
| 62 | { | ||
| 63 | fn from(value: T) -> Self { | ||
| 64 | match value.into() { | ||
| 65 | ApiError::Client(e) => Self::fail(e.kind(), e.into_message()), | ||
| 66 | ApiError::Server(e) => Self::fail(e.kind(), e.into_message()), | ||
| 67 | } | ||
| 68 | } | ||
| 69 | } | ||
