281c84b7bf
Reviewed-on: http://192.168.35.82/git/GenarrativeAI/Genarrative/pulls/142 Co-authored-by: Linghong <ink29535@proton.me> Co-committed-by: Linghong <ink29535@proton.me>
160 lines
5.3 KiB
Rust
160 lines
5.3 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::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_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 {
|
|
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(), "请求体过大");
|
|
}
|
|
}
|