253f99d921
Project CI / AI game creator shell Rust crates (push) Successful in 1m30s
Project CI / AI game creator shell Rust smoke (push) Successful in 1m59s
Project CI / AI game creator shell Rust lane 2/2 (push) Failing after 5m26s
Project CI / Backend tests (push) Successful in 4m13s
Project CI / Frontend tests (push) Has been cancelled
Project CI / Native shell tests (push) Has been cancelled
Project CI / AI game creator shell web tests (push) Has been cancelled
Project CI / AI game creator shell Rust lane 1/2 (push) Has been cancelled
Project CI / Repository checks (push) Has been cancelled
- api-server 的错误响应改用 attach_request_context 建立的 CURRENT_REQUEST_CONTEXT(tokio task_local),错误 envelope 与成功 envelope 一样带 meta.requestId / meta.operation,脱离请求任务时退回原形状 - 越权隔离脚本新增成功/失败 envelope 断言:修复前错误响应 requestId 为空让断言变红,修复后 23 项 PASS - 媒体链路脚本扩展审核治理段:普通作者不能提交审核动作、更新待审与被拒都不改变在线旧版 URL 与可玩内容、审核结论可在后台追溯,44 项 PASS - 游戏分发里程碑阶段 A 第 6 条、阶段 B 第 1/2 条改为已勾选并写入取证,阶段 B 其余条目列出具体缺口 - decision-log 补记错误 envelope 同一份 meta 与「按可消费取证」两条口径
175 lines
6.0 KiB
Rust
175 lines
6.0 KiB
Rust
use axum::{
|
|
http::StatusCode,
|
|
http::{HeaderMap, HeaderValue},
|
|
response::{IntoResponse, Response},
|
|
};
|
|
use serde_json::Value;
|
|
use shared_contracts::api::ApiErrorPayload;
|
|
|
|
use crate::{
|
|
api_response::json_error_body,
|
|
request_context::{CURRENT_REQUEST_CONTEXT, RequestContext},
|
|
};
|
|
|
|
#[derive(Debug)]
|
|
pub struct AppError {
|
|
status_code: StatusCode,
|
|
code: &'static str,
|
|
message: String,
|
|
details: Option<Value>,
|
|
headers: HeaderMap,
|
|
}
|
|
|
|
impl AppError {
|
|
pub fn from_status(status_code: StatusCode) -> Self {
|
|
let (code, message) = resolve_http_error(status_code);
|
|
|
|
Self {
|
|
status_code,
|
|
code,
|
|
message: message.to_string(),
|
|
details: None,
|
|
headers: HeaderMap::new(),
|
|
}
|
|
}
|
|
|
|
pub fn code(&self) -> &'static str {
|
|
self.code
|
|
}
|
|
|
|
pub fn status_code(&self) -> StatusCode {
|
|
self.status_code
|
|
}
|
|
|
|
pub fn message(&self) -> &str {
|
|
&self.message
|
|
}
|
|
|
|
pub fn details(&self) -> Option<&Value> {
|
|
self.details.as_ref()
|
|
}
|
|
|
|
pub fn body_text(&self) -> String {
|
|
// 批处理任务不能只读 HTTP 状态文案,否则 DashScope 返回的真实失败原因会被压成“上游服务请求失败”。
|
|
self.details
|
|
.as_ref()
|
|
.and_then(|details| details.get("message"))
|
|
.and_then(Value::as_str)
|
|
.map(str::trim)
|
|
.filter(|message| !message.is_empty())
|
|
.unwrap_or(self.message.as_str())
|
|
.to_string()
|
|
}
|
|
|
|
pub fn with_message(mut self, message: impl Into<String>) -> Self {
|
|
self.message = message.into();
|
|
self
|
|
}
|
|
|
|
pub fn with_code(mut self, code: &'static str) -> Self {
|
|
self.code = code;
|
|
self
|
|
}
|
|
|
|
pub fn with_details(mut self, details: Value) -> Self {
|
|
self.details = Some(details);
|
|
self
|
|
}
|
|
|
|
/// 中文注释:在已有 details 上补一个字段,而不是像 `with_details` 那样整体替换。
|
|
/// 用于给沿途传上来的错误追加旁路信息(例如「失败发生在持久化开始之后」),同时保留
|
|
/// 下游原本写入的 provider / message 等字段——客户端要靠 message 定位,靠新字段决策。
|
|
pub fn with_detail_field(mut self, key: &'static str, value: Value) -> Self {
|
|
match self.details.take() {
|
|
Some(Value::Object(mut object)) => {
|
|
object.insert(key.to_string(), value);
|
|
self.details = Some(Value::Object(object));
|
|
}
|
|
// 中文注释:details 为空或不是对象时按对象重建。本仓库的 details 一律是对象,
|
|
// 走到后一个分支说明调用方写法有变,宁可保留标记也不静默丢弃。
|
|
_ => {
|
|
self.details = Some(serde_json::json!({ key: value }));
|
|
}
|
|
}
|
|
self
|
|
}
|
|
|
|
pub fn with_header(mut self, name: &'static str, value: HeaderValue) -> Self {
|
|
self.headers.insert(name, value);
|
|
self
|
|
}
|
|
|
|
pub fn into_response_with_context(self, request_context: Option<&RequestContext>) -> Response {
|
|
let status_code = self.status_code;
|
|
let payload = self.to_payload();
|
|
let mut response =
|
|
(status_code, json_error_body(request_context, &payload)).into_response();
|
|
response.headers_mut().extend(self.headers);
|
|
response
|
|
}
|
|
|
|
fn to_payload(&self) -> ApiErrorPayload {
|
|
ApiErrorPayload::new(self.code, self.message.clone(), self.details.clone())
|
|
}
|
|
}
|
|
|
|
impl IntoResponse for AppError {
|
|
fn into_response(self) -> Response {
|
|
// 绝大多数 handler 错误是在 `attach_request_context` 的任务里转成响应的:
|
|
// 这里带上同一份 requestId / operation,错误 envelope 才与成功 envelope 一致;
|
|
// 脱离请求任务(测试、后台任务)时退回无上下文的形状。
|
|
if CURRENT_REQUEST_CONTEXT.try_with(|_| ()).is_ok() {
|
|
CURRENT_REQUEST_CONTEXT.with(|context| self.into_response_with_context(Some(context)))
|
|
} else {
|
|
self.into_response_with_context(None)
|
|
}
|
|
}
|
|
}
|
|
|
|
impl std::fmt::Display for AppError {
|
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
formatter.write_str(self.body_text().as_str())
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for AppError {}
|
|
|
|
impl From<AppError> for Response {
|
|
fn from(error: AppError) -> Self {
|
|
error.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::GONE => ("GONE", "资源已失效"),
|
|
StatusCode::NOT_IMPLEMENTED => ("NOT_IMPLEMENTED", "功能暂未实现"),
|
|
StatusCode::CONFLICT => ("CONFLICT", "请求冲突"),
|
|
StatusCode::PAYLOAD_TOO_LARGE => ("PAYLOAD_TOO_LARGE", "请求体过大"),
|
|
StatusCode::TOO_MANY_REQUESTS => ("TOO_MANY_REQUESTS", "请求过于频繁"),
|
|
StatusCode::GATEWAY_TIMEOUT => ("GATEWAY_TIMEOUT", "上游服务请求超时"),
|
|
StatusCode::BAD_GATEWAY => ("UPSTREAM_ERROR", "上游服务请求失败"),
|
|
StatusCode::SERVICE_UNAVAILABLE => ("SERVICE_UNAVAILABLE", "服务暂不可用"),
|
|
_ if status_code.is_client_error() => ("BAD_REQUEST", "请求参数不合法"),
|
|
_ => ("INTERNAL_SERVER_ERROR", "服务器内部错误"),
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn payload_too_large_keeps_a_distinct_error_contract() {
|
|
let error = AppError::from_status(StatusCode::PAYLOAD_TOO_LARGE);
|
|
|
|
assert_eq!(error.status_code(), StatusCode::PAYLOAD_TOO_LARGE);
|
|
assert_eq!(error.code(), "PAYLOAD_TOO_LARGE");
|
|
assert_eq!(error.message(), "请求体过大");
|
|
}
|
|
}
|