fix(routes): 请求体解析失败与方法不允许都回到业务信封
- 新增宽松 JSON 抽取器:畸形 body 不再返回 axum 默认的 text/plain 400,
改为 HTTP 200 + code 400 + 上游原文「请求体格式有误,请检查 JSON 结构与字段类型」
- 方法不允许返回 JSON(405 + code/msg),不再是空体
- /Detail 的查无文案逐实体对齐上游:Dataset 与 Resource 文案不同
- /Detail 路径改从注册表取,不再硬编码
- 补 HTTP 级用例覆盖 GET {id} / POST / PUT / DELETE 与聚合体子表
Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
1 parent
0f84fbdb83
commit
5d74354944
5 files changed
+441
-57
No files matched your search
+14
-1
@@ -880,6 +880,17 @@ fn child_tables(spec: &TableSpec) -> &'static [(&'static str, &'static str)] {
|
||||
}
|
||||
}
|
||||
|
||||
/// `/Detail` 聚合体的「查无」文案(逐字对齐上游)。
|
||||
///
|
||||
/// - `Dataset` ⇒ 「数据集不存在或资源已删除」(上游 `DatasetController#detailOf`,`:142`)
|
||||
/// - 其余 ⇒ 「记录不存在或已删除」(上游 `ResourceController#detailOf`,`:210`)
|
||||
fn detail_not_found_msg(api_name: &str) -> &'static str {
|
||||
match api_name {
|
||||
"Dataset" => "数据集不存在或资源已删除",
|
||||
_ => "记录不存在或已删除",
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /api/ssw/tdc/{Entity}/{id}/Detail` —— 上游 `ResourceController` / `DatasetController`
|
||||
/// 的**只读聚合体**(`ResourceService.withChildren`):资源行 + 两张子表。
|
||||
///
|
||||
@@ -911,7 +922,9 @@ pub async fn detail_aggregate(
|
||||
};
|
||||
let row = match rows.first() {
|
||||
Some(row) => row,
|
||||
None => return ActionResult::fail("记录不存在或已删除").into_response(),
|
||||
None => {
|
||||
return ActionResult::fail(detail_not_found_msg(spec.api_name)).into_response()
|
||||
}
|
||||
};
|
||||
let mut data = row_to_json(row);
|
||||
for (key, table) in children {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//! 宽松 JSON 请求体:解析失败 ⇒ 业务信封(逐字对齐上游 `SswExceptionHandler`)。
|
||||
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::{FromRequest, Request};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::envelope::ActionResult;
|
||||
|
||||
/// 上游的原文拒因(`SswExceptionHandler#handleNotReadable`)。
|
||||
///
|
||||
/// 🔴 上游 `ActionResult.fail(String)` 的 `code` **恒为 400**
|
||||
/// (`jnpf.base.ActionResult` 字节码:`sipush 400`),且 Spring 给 **HTTP 200**
|
||||
/// ⇒ 业务失败 = HTTP 200 + `{code:400,msg:…}`。
|
||||
pub const BODY_FORMAT_ERROR: &str = "请求体格式有误,请检查 JSON 结构与字段类型";
|
||||
|
||||
/// 请求体(宽松 JSON)。
|
||||
///
|
||||
/// 🔴 **为什么不用 axum 的 `Json<T>`**:
|
||||
/// `Json<T>` 解析失败时返回 `JsonRejection` ⇒ axum 渲染成 **HTTP 400 + `text/plain`**,
|
||||
/// body 不是 JSON ⇒ 上游前端拦截器 `body.msg` 取不到(`body` 是字符串)
|
||||
/// ⇒ 用户看到 "Request failed with status code 400" 的英文兜底。
|
||||
/// 本抽取器把同类失败**如实回传成业务信封**,与上游逐字一致。
|
||||
///
|
||||
/// 🔴 **不校验 Content-Type** ⇒ 上游的 `HttpMediaTypeNotSupportedException`(415)在本仓**不发生**;
|
||||
/// 错误媒体类型会以「JSON 解析失败」的口径回报
|
||||
/// (上游的 415 落到 JNPF 全局兜底,形状未知 ⇒ 这是**已登记的刻意分歧**)。
|
||||
///
|
||||
/// ⚠️ **空 body ⇒ `None`**(保留既有语义:POST / PUT 允许不带 body ⇒ 引擎按缺省值走)。
|
||||
pub struct JsonBody(pub Option<Value>);
|
||||
|
||||
impl<S> FromRequest<S> for JsonBody
|
||||
where
|
||||
S: Send + Sync,
|
||||
{
|
||||
/// 🔴 拒绝 = **完整的业务信封响应**(不是 axum 的默认文本)⇒ 解析失败也走 HTTP 200 + code 400。
|
||||
type Rejection = Response;
|
||||
|
||||
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
|
||||
let bytes = Bytes::from_request(req, state)
|
||||
.await
|
||||
.map_err(|_| ActionResult::fail(BODY_FORMAT_ERROR).into_response())?;
|
||||
if bytes.is_empty() {
|
||||
return Ok(JsonBody(None));
|
||||
}
|
||||
match serde_json::from_slice::<Value>(&bytes) {
|
||||
Ok(v) => Ok(JsonBody(Some(v))),
|
||||
Err(_) => Err(ActionResult::fail(BODY_FORMAT_ERROR).into_response()),
|
||||
}
|
||||
}
|
||||
}
|
||||
+55
-36
@@ -18,6 +18,7 @@ use axum::routing::get;
|
||||
use axum::Router;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::body::JsonBody;
|
||||
use crate::auth::Principal;
|
||||
use crate::crud;
|
||||
use crate::registry::{self, TableSpec};
|
||||
@@ -30,51 +31,61 @@ pub fn router() -> Router<AppState> {
|
||||
r = r
|
||||
.route(
|
||||
s.path,
|
||||
get(move |State(st): State<AppState>, q: RawQuery, p: Option<Extension<Principal>>| {
|
||||
let params = crud::parse_query(q.0.as_deref());
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::list(&st, s, ¶ms, principal.as_ref()).await }
|
||||
})
|
||||
get(
|
||||
move |State(st): State<AppState>,
|
||||
q: RawQuery,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let params = crud::parse_query(q.0.as_deref());
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::list(&st, s, ¶ms, principal.as_ref()).await }
|
||||
},
|
||||
)
|
||||
.post(
|
||||
move |State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>,
|
||||
b: Option<axum::Json<Value>>| {
|
||||
b: JsonBody| {
|
||||
let principal = p.map(|e| e.0);
|
||||
let body = b.map(|axum::Json(v)| v).unwrap_or(Value::Null);
|
||||
let body = b.0.unwrap_or(Value::Null);
|
||||
async move { crud::create(&st, s, &body, principal.as_ref()).await }
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{}/All", s.path),
|
||||
get(move |State(st): State<AppState>, q: RawQuery, p: Option<Extension<Principal>>| {
|
||||
let params = crud::parse_query(q.0.as_deref());
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::all(&st, s, ¶ms, principal.as_ref()).await }
|
||||
}),
|
||||
get(
|
||||
move |State(st): State<AppState>,
|
||||
q: RawQuery,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let params = crud::parse_query(q.0.as_deref());
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::all(&st, s, ¶ms, principal.as_ref()).await }
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{}/{{id}}", s.path),
|
||||
get(move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::detail(&st, s, &id, principal.as_ref()).await }
|
||||
})
|
||||
get(
|
||||
move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::detail(&st, s, &id, principal.as_ref()).await }
|
||||
},
|
||||
)
|
||||
.put(
|
||||
move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>,
|
||||
b: Option<axum::Json<Value>>| {
|
||||
b: JsonBody| {
|
||||
let principal = p.map(|e| e.0);
|
||||
let body = b.map(|axum::Json(v)| v).unwrap_or(Value::Null);
|
||||
let body = b.0.unwrap_or(Value::Null);
|
||||
async move { crud::update(&st, s, &id, &body, principal.as_ref()).await }
|
||||
},
|
||||
)
|
||||
.delete(
|
||||
move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::delete(&st, s, &id, principal.as_ref()).await }
|
||||
},
|
||||
@@ -95,22 +106,30 @@ pub fn router() -> Router<AppState> {
|
||||
registry::find("Dataset").expect("Dataset 必须在注册表里");
|
||||
r = r
|
||||
.route(
|
||||
"/api/ssw/tdc/Resource/{id}/Detail",
|
||||
get(move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::detail_aggregate(&st, res_spec, &id, principal.as_ref()).await }
|
||||
}),
|
||||
&format!("{}/{{id}}/Detail", res_spec.path),
|
||||
get(
|
||||
move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move {
|
||||
crud::detail_aggregate(&st, res_spec, &id, principal.as_ref()).await
|
||||
}
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/api/ssw/tdc/Dataset/{id}/Detail",
|
||||
get(move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::detail_aggregate(&st, ds_spec, &id, principal.as_ref()).await }
|
||||
}),
|
||||
&format!("{}/{{id}}/Detail", ds_spec.path),
|
||||
get(
|
||||
move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move {
|
||||
crud::detail_aggregate(&st, ds_spec, &id, principal.as_ref()).await
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
r
|
||||
|
||||
+22
-1
@@ -1,10 +1,14 @@
|
||||
//! 按域装配的 axum Router。
|
||||
|
||||
pub mod auth;
|
||||
pub mod body;
|
||||
pub mod crud;
|
||||
pub mod health;
|
||||
|
||||
use axum::Router;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::{Json, Router};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::state::AppState;
|
||||
|
||||
@@ -19,5 +23,22 @@ pub fn build_router(state: AppState) -> Router<AppState> {
|
||||
.merge(health::router())
|
||||
.merge(auth::router())
|
||||
.merge(crud::router())
|
||||
// 🔴 方法不允许 ⇒ JSON(axum 默认是**空体 405** ⇒ 前端拿不到 `msg`)
|
||||
.method_not_allowed_fallback(method_not_allowed)
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
/// 方法不允许 ⇒ JSON。
|
||||
///
|
||||
/// 🔴 形状:HTTP 405 + `{"code":405,"msg":"方法不被允许","data":null}`
|
||||
/// —— 前端 axios 的 error 分支读 `error.response.data.msg` ⇒ 能如实显示。
|
||||
///
|
||||
/// ⚠️ 上游(Spring)这条路径落到 JNPF 全局兜底,形状**未知**
|
||||
/// ⇒ 本仓取「保留 405 语义 + 补 JSON body」,是**已登记的刻意分歧**。
|
||||
async fn method_not_allowed() -> Response {
|
||||
(
|
||||
StatusCode::METHOD_NOT_ALLOWED,
|
||||
Json(json!({"code": 405, "msg": "方法不被允许", "data": null})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Reference in new issue
Block a user