build: add api server error normalization layer

This commit is contained in:
2026-04-21 01:24:09 +08:00
parent 0ac5606a41
commit cb069de32e
8 changed files with 146 additions and 2 deletions

View File

@@ -0,0 +1,73 @@
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde::Serialize;
use serde_json::Value;
#[derive(Debug)]
pub struct AppError {
status_code: StatusCode,
code: &'static str,
message: &'static str,
details: Option<Value>,
}
#[derive(Debug, Serialize)]
struct LegacyApiErrorBody {
error: LegacyApiErrorPayload,
}
#[derive(Debug, Serialize)]
struct LegacyApiErrorPayload {
code: &'static str,
message: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
details: Option<Value>,
}
impl AppError {
pub fn from_status(status_code: StatusCode) -> Self {
let (code, message) = resolve_http_error(status_code);
Self {
status_code,
code,
message,
details: None,
}
}
pub fn code(&self) -> &'static str {
self.code
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let body = LegacyApiErrorBody {
error: LegacyApiErrorPayload {
code: self.code,
message: self.message,
details: self.details,
},
};
(self.status_code, Json(body)).into_response()
}
}
fn resolve_http_error(status_code: StatusCode) -> (&'static str, &'static str) {
match status_code {
StatusCode::BAD_REQUEST => ("BAD_REQUEST", "请求参数不合法"),
StatusCode::UNAUTHORIZED => ("UNAUTHORIZED", "未授权访问"),
StatusCode::FORBIDDEN => ("FORBIDDEN", "禁止访问"),
StatusCode::NOT_FOUND => ("NOT_FOUND", "资源不存在"),
StatusCode::CONFLICT => ("CONFLICT", "请求冲突"),
StatusCode::TOO_MANY_REQUESTS => ("TOO_MANY_REQUESTS", "请求过于频繁"),
StatusCode::BAD_GATEWAY => ("UPSTREAM_ERROR", "上游服务请求失败"),
_ if status_code.is_client_error() => ("BAD_REQUEST", "请求参数不合法"),
_ => ("INTERNAL_SERVER_ERROR", "服务器内部错误"),
}
}