| 1 | use axum::http::StatusCode; |
| 2 | use axum::response::{IntoResponse, Response}; |
| 3 | use axum::Json; |
| 4 | use serde_json::json; |
| 5 | use utopia_core::AppError; |
| 6 | |
| 7 | /// axum 响应包装(orphan rule:IntoResponse 不能直接实现在 core 类型上)。 |
| 8 | pub struct ApiErr(pub AppError); |
| 9 | |
| 10 | impl<E: Into<AppError>> From<E> for ApiErr { |
| 11 | fn from(e: E) -> Self { |
| 12 | ApiErr(e.into()) |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | pub type ApiResult<T> = Result<T, ApiErr>; |
| 17 | |
| 18 | impl IntoResponse for ApiErr { |
| 19 | fn into_response(self) -> Response { |
| 20 | // code 与 detail 只有 Invalid 才有;其余保持原样,转换可以一条条推进 |
| 21 | let mut code: Option<&'static str> = None; |
| 22 | let mut detail: Option<String> = None; |
| 23 | let (status, message) = match &self.0 { |
| 24 | AppError::Invalid { |
| 25 | code: c, |
| 26 | message, |
| 27 | detail: d, |
| 28 | } => { |
| 29 | code = Some(c); |
| 30 | detail.clone_from(d); |
| 31 | (StatusCode::UNPROCESSABLE_ENTITY, message.clone()) |
| 32 | } |
| 33 | AppError::NotFound => (StatusCode::NOT_FOUND, self.0.to_string()), |
| 34 | AppError::Unauthorized => (StatusCode::UNAUTHORIZED, self.0.to_string()), |
| 35 | AppError::Forbidden => (StatusCode::FORBIDDEN, self.0.to_string()), |
| 36 | AppError::Conflict(m) => (StatusCode::CONFLICT, m.clone()), |
| 37 | AppError::Validation(m) => (StatusCode::UNPROCESSABLE_ENTITY, m.clone()), |
| 38 | AppError::Db(e) => { |
| 39 | tracing::error!(error = %e, "database error"); |
| 40 | ( |
| 41 | StatusCode::INTERNAL_SERVER_ERROR, |
| 42 | "Internal server error".into(), |
| 43 | ) |
| 44 | } |
| 45 | AppError::Other(e) => { |
| 46 | tracing::error!(error = %e, "internal error"); |
| 47 | ( |
| 48 | StatusCode::INTERNAL_SERVER_ERROR, |
| 49 | "Internal server error".into(), |
| 50 | ) |
| 51 | } |
| 52 | }; |
| 53 | let mut body = json!({ "error": message }); |
| 54 | if let Some(c) = code { |
| 55 | body["code"] = json!(c); |
| 56 | } |
| 57 | if let Some(d) = detail { |
| 58 | body["detail"] = json!(d); |
| 59 | } |
| 60 | (status, Json(body)).into_response() |
| 61 | } |
| 62 | } |