From 8253fbc497cc502777b1e81cb6fef0125babab3e Mon Sep 17 00:00:00 2001 From: Zyy Date: Thu, 19 Nov 2026 15:41:32 +0800 Subject: [PATCH] fix(errors): show specific causes in admin feedback and request records --- .../gateway-admin/src/model/account_groups.rs | 28 ++-- backend/crates/gateway-admin/src/model/mod.rs | 2 - .../crates/gateway-admin/src/ports/store.rs | 1 + .../src/use_case/account_groups.rs | 16 ++- .../gateway-admin/src/use_case/client_keys.rs | 1 - .../gateway-admin/src/use_case/error.rs | 28 ++-- .../gateway-api/src/admin/account_groups.rs | 14 +- .../gateway-api/src/admin/client_keys.rs | 2 +- .../src/admin/observability/presenter.rs | 9 +- .../src/admin/observability/query.rs | 2 +- backend/crates/gateway-api/src/admin/wire.rs | 4 +- .../crates/gateway-api/tests/admin/errors.rs | 6 + .../crates/gateway-api/tests/admin/wire.rs | 4 +- .../src/postgres/account_groups.rs | 21 ++- .../providers/openai/src/provider/failure.rs | 128 +++++++++++------- .../tests/provider/contract/error_details.rs | 3 + .../openai/tests/provider/contract/mod.rs | 1 + .../providers/xai/src/provider/failure.rs | 29 +--- .../providers/xai/src/transport/canonical.rs | 27 ++-- .../providers/xai/src/transport/inference.rs | 55 +++++++- .../providers/xai/src/transport/network.rs | 46 +++---- .../xai/tests/transport/canonical.rs | 4 + .../providers/xai/tests/transport/network.rs | 4 + docs/api.md | 2 +- frontend/src/api/request/plugins/error.ts | 2 +- frontend/src/api/request/plugins/raw.ts | 4 +- .../src/components/usage/UsageErrorCell.vue | 13 +- frontend/src/i18n/locales/en/common.json | 8 +- frontend/src/i18n/locales/zh-Hans/common.json | 10 +- frontend/src/i18n/locales/zh-Hant/common.json | 10 +- .../accounts/composables/useAccountEditor.ts | 5 +- 31 files changed, 302 insertions(+), 187 deletions(-) diff --git a/backend/crates/gateway-admin/src/model/account_groups.rs b/backend/crates/gateway-admin/src/model/account_groups.rs index 9a4bc4bbb..d1d63894f 100644 --- a/backend/crates/gateway-admin/src/model/account_groups.rs +++ b/backend/crates/gateway-admin/src/model/account_groups.rs @@ -14,15 +14,25 @@ use super::{PageSize, Revision, observability::DecimalAmount}; pub fn validate_group_fields( name: &str, description: Option<&str>, -) -> Result<(), super::AdminModelError> { - if name.trim() != name - || name.is_empty() - || name.chars().count() > 100 - || name.chars().any(char::is_control) - || description - .is_some_and(|value| value.len() > 4096 || value.chars().any(char::is_control)) - { - return Err(super::AdminModelError::InvalidAccountGroupFields); +) -> Result<(), super::AdminError> { + if name.trim().is_empty() { + return Err(super::AdminError::invalid("请输入账号组名称")); + } + if name.chars().count() > 100 { + return Err(super::AdminError::invalid("账号组名称最多 100 个字符")); + } + if name.trim() != name || name.chars().any(char::is_control) { + return Err(super::AdminError::invalid( + "账号组名称不能包含首尾空白或控制字符", + )); + } + if let Some(description) = description { + if description.len() > 4096 { + return Err(super::AdminError::invalid("账号组描述最多 4096 字节")); + } + if description.chars().any(char::is_control) { + return Err(super::AdminError::invalid("账号组描述不能包含控制字符")); + } } Ok(()) } diff --git a/backend/crates/gateway-admin/src/model/mod.rs b/backend/crates/gateway-admin/src/model/mod.rs index ab422eb03..75e7a100b 100644 --- a/backend/crates/gateway-admin/src/model/mod.rs +++ b/backend/crates/gateway-admin/src/model/mod.rs @@ -236,8 +236,6 @@ pub enum AdminModelError { InvalidPageSize(u16), #[error("observability page size {0} is outside 1..=100")] InvalidObservabilityPageSize(u16), - #[error("account group name or description is invalid")] - InvalidAccountGroupFields, #[error("client key group IDs are duplicated or exceed 1000 entries")] InvalidClientKeyGroups, #[error("client key page size must be inside 1..=65535")] diff --git a/backend/crates/gateway-admin/src/ports/store.rs b/backend/crates/gateway-admin/src/ports/store.rs index 748e0ce6c..887338762 100644 --- a/backend/crates/gateway-admin/src/ports/store.rs +++ b/backend/crates/gateway-admin/src/ports/store.rs @@ -480,6 +480,7 @@ pub trait AccountGroupStore: Send + Sync { context: &MutationContext, ) -> AdminStoreResult; + /// 仍有 API Key 引用分组时返回 Conflict async fn delete_account_group( &self, command: DeleteAccountGroup, diff --git a/backend/crates/gateway-admin/src/use_case/account_groups.rs b/backend/crates/gateway-admin/src/use_case/account_groups.rs index a3ba763c2..cdad47a2d 100644 --- a/backend/crates/gateway-admin/src/use_case/account_groups.rs +++ b/backend/crates/gateway-admin/src/use_case/account_groups.rs @@ -24,7 +24,7 @@ use crate::{ NewAccountGroup, SetAccountGroupEnabled, UpdateAccountGroup, }, }, - ports::store::{AccountGroupStore, AccountRuntimeStore}, + ports::store::{AccountGroupStore, AccountRuntimeStore, AdminStoreErrorKind}, }; use super::{map_store_error, publish_committed}; @@ -159,8 +159,7 @@ impl AccountGroupService for DefaultAccountGroupService { crate::model::account_groups::validate_group_fields( &command.name, command.description.as_deref(), - ) - .map_err(|_| AdminError::invalid("账号组请求不合法"))?; + )?; let id = AccountGroupId::new(format!("grp_{}", Uuid::now_v7().simple())) .map_err(|_| AdminError::internal("创建账号组 ID 失败"))?; self.publish( @@ -189,8 +188,7 @@ impl AccountGroupService for DefaultAccountGroupService { crate::model::account_groups::validate_group_fields( &command.name, command.description.as_deref(), - ) - .map_err(|_| AdminError::invalid("账号组请求不合法"))?; + )?; self.publish(self.store.update_account_group(command, context).await) .await } @@ -209,8 +207,12 @@ impl AccountGroupService for DefaultAccountGroupService { context: &MutationContext, command: DeleteAccountGroup, ) -> Result { - self.publish(self.store.delete_account_group(command, context).await) - .await + match self.store.delete_account_group(command, context).await { + Err(error) if error.kind() == AdminStoreErrorKind::Conflict => { + Err(AdminError::conflict("分组仍绑定 API Key,请先解除绑定").with_source(error)) + } + result => self.publish(result).await, + } } } diff --git a/backend/crates/gateway-admin/src/use_case/client_keys.rs b/backend/crates/gateway-admin/src/use_case/client_keys.rs index c95098ef1..b4ba55844 100644 --- a/backend/crates/gateway-admin/src/use_case/client_keys.rs +++ b/backend/crates/gateway-admin/src/use_case/client_keys.rs @@ -314,7 +314,6 @@ impl ClientKeyService for DefaultClientKeyService { fn map_client_key_write_error(error: AdminStoreError) -> AdminError { match error.kind() { - AdminStoreErrorKind::DuplicateName => AdminError::conflict("名称已存在"), AdminStoreErrorKind::Conflict => AdminError::conflict("API Key 已存在,请使用其他密钥"), _ => map_store_error(error, "client API key"), } diff --git a/backend/crates/gateway-admin/src/use_case/error.rs b/backend/crates/gateway-admin/src/use_case/error.rs index 8a17778dc..4b0b43ae5 100644 --- a/backend/crates/gateway-admin/src/use_case/error.rs +++ b/backend/crates/gateway-admin/src/use_case/error.rs @@ -4,20 +4,15 @@ use crate::model::{AdminError, AdminErrorKind}; use crate::ports::store::{AdminStoreError, AdminStoreErrorKind}; pub(super) fn map_store_error(error: AdminStoreError, resource: &'static str) -> AdminError { - let kind = match error.kind() { - AdminStoreErrorKind::Invalid => AdminErrorKind::Invalid, - AdminStoreErrorKind::NotFound => AdminErrorKind::NotFound, - AdminStoreErrorKind::StaleRevision - | AdminStoreErrorKind::DuplicateName - | AdminStoreErrorKind::Conflict => AdminErrorKind::Conflict, - AdminStoreErrorKind::Unavailable => AdminErrorKind::Unavailable, - }; - let message = match kind { - AdminErrorKind::Invalid => "请求参数不合法", - AdminErrorKind::NotFound => "请求的资源不存在", - AdminErrorKind::Conflict => "当前资源状态冲突,请刷新后重试", - AdminErrorKind::Unavailable => "依赖服务暂不可用", - _ => "服务内部错误", + let (kind, message) = match error.kind() { + AdminStoreErrorKind::Invalid => (AdminErrorKind::Invalid, "请求参数不合法"), + AdminStoreErrorKind::NotFound => (AdminErrorKind::NotFound, "请求的资源不存在"), + AdminStoreErrorKind::StaleRevision => { + (AdminErrorKind::Conflict, "数据已更新,请刷新后再操作") + } + AdminStoreErrorKind::DuplicateName => (AdminErrorKind::Conflict, "名称已存在"), + AdminStoreErrorKind::Conflict => (AdminErrorKind::Conflict, "当前资源状态不允许此操作"), + AdminStoreErrorKind::Unavailable => (AdminErrorKind::Unavailable, "存储服务暂不可用"), }; AdminError::new(kind, message).with_source(OperationFailure { operation: resource, @@ -49,9 +44,8 @@ pub(super) fn map_provider_error( ProviderAdminErrorKind::Conflict => "服务商资源状态冲突,请刷新后重试", ProviderAdminErrorKind::BadGateway => "上游服务请求失败", ProviderAdminErrorKind::Ambiguous => "上游执行结果未知,请刷新状态后再决定是否重试", - ProviderAdminErrorKind::Unavailable | ProviderAdminErrorKind::CredentialRefreshRequired => { - "服务商暂不可用" - } + ProviderAdminErrorKind::Unavailable => "服务商暂不可用", + ProviderAdminErrorKind::CredentialRefreshRequired => "账号凭据需要刷新", ProviderAdminErrorKind::Internal => "服务内部错误", }; AdminError::new(kind, error.public_message().unwrap_or(message)).with_source(OperationFailure { diff --git a/backend/crates/gateway-api/src/admin/account_groups.rs b/backend/crates/gateway-api/src/admin/account_groups.rs index 52ee7953a..8562f9661 100644 --- a/backend/crates/gateway-api/src/admin/account_groups.rs +++ b/backend/crates/gateway-api/src/admin/account_groups.rs @@ -51,7 +51,6 @@ impl From for AccountGrou } const DEFAULT_PAGE_SIZE: u32 = 50; -const MAX_PAGE_SIZE: u32 = 200; #[derive(Debug, Clone, Default, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -66,7 +65,7 @@ impl ListAccountGroupsQuery { fn into_command(self) -> Result { let page = self.page.unwrap_or(1); let page_size = self.page_size.unwrap_or(DEFAULT_PAGE_SIZE); - if page == 0 || page_size == 0 || page_size > MAX_PAGE_SIZE { + if page == 0 { return Err(WireValidationError::new("page")); } let search = self @@ -507,11 +506,16 @@ fn group_color(value: &str) -> Result { fn validate_group_fields(name: &str, description: Option<&str>) -> Result<(), AdminError> { gateway_admin::model::account_groups::validate_group_fields(name, description) - .map_err(|_| AdminError::bad_request("账号组请求不合法")) + .map_err(map_admin_service_error) } -fn map_wire_error(_: WireValidationError) -> AdminError { - AdminError::bad_request("账号组查询参数不合法") +fn map_wire_error(error: WireValidationError) -> AdminError { + match error.field() { + "page" => AdminError::bad_request("页码须大于 0"), + "pageSize" => AdminError::bad_request(format!("每页数量须为 1 至 {}", PageSize::MAX)), + "search" => AdminError::bad_request("搜索内容最多 256 字节,不能包含控制字符"), + field => AdminError::bad_request(format!("{field} 字段不合法")), + } } fn map_service_error(error: gateway_admin::model::AdminError) -> AdminError { diff --git a/backend/crates/gateway-api/src/admin/client_keys.rs b/backend/crates/gateway-api/src/admin/client_keys.rs index 5692cc3ce..3ad31b26e 100644 --- a/backend/crates/gateway-api/src/admin/client_keys.rs +++ b/backend/crates/gateway-api/src/admin/client_keys.rs @@ -1092,7 +1092,7 @@ fn map_wire_error(error: WireValidationError) -> AdminError { "search" => "搜索内容过长或包含控制字符", "sortBy" => "排序字段不受支持", "sortDirection" => "排序方向必须为 asc(升序)或 desc(降序)", - _ => "API Key 请求参数不合法", + field => return AdminError::bad_request(format!("{field} 字段不合法")), }; AdminError::bad_request(message) } diff --git a/backend/crates/gateway-api/src/admin/observability/presenter.rs b/backend/crates/gateway-api/src/admin/observability/presenter.rs index 841e69d69..ca476417f 100644 --- a/backend/crates/gateway-api/src/admin/observability/presenter.rs +++ b/backend/crates/gateway-api/src/admin/observability/presenter.rs @@ -1410,7 +1410,14 @@ pub(crate) fn map_wire_error(error: WireValidationError) -> AdminError { "dimension" => "诊断维度不合法", "id" => "用量记录 ID 不能为空", "cursor" => "观测数据游标不合法", - _ => "观测查询参数不合法", + "currentPage" => "页码须大于 0", + "pageSize" => { + return AdminError::bad_request(format!("每页数量须为 1 至 {}", DomainPageSize::MAX)); + } + "status" => "请求状态须为 success、error 或 all", + "errorOrigin" => "错误来源须为 proxy、upstream、connection 或 unknown", + "errorOriginStatus" => "仅错误请求支持按错误来源筛选", + field => return AdminError::bad_request(format!("{field} 字段不合法")), }; AdminError::bad_request(message) } diff --git a/backend/crates/gateway-api/src/admin/observability/query.rs b/backend/crates/gateway-api/src/admin/observability/query.rs index 522ea454a..9da11f9af 100644 --- a/backend/crates/gateway-api/src/admin/observability/query.rs +++ b/backend/crates/gateway-api/src/admin/observability/query.rs @@ -367,7 +367,7 @@ pub(crate) fn usage_command( Some(_) => return Err(WireValidationError::new("errorOrigin")), }), (None | Some("success" | "all"), Some(_)) => { - return Err(WireValidationError::new("errorOrigin")); + return Err(WireValidationError::new("errorOriginStatus")); } (Some(_), _) => return Err(WireValidationError::new("status")), }, diff --git a/backend/crates/gateway-api/src/admin/wire.rs b/backend/crates/gateway-api/src/admin/wire.rs index 350da4816..526d49de4 100644 --- a/backend/crates/gateway-api/src/admin/wire.rs +++ b/backend/crates/gateway-api/src/admin/wire.rs @@ -215,12 +215,12 @@ const METHOD_NOT_ALLOWED: AdminErrorSpec = AdminErrorSpec::new( const TOO_MANY_LOGIN_ATTEMPTS: AdminErrorSpec = AdminErrorSpec::new( StatusCode::TOO_MANY_REQUESTS, AdminErrorCode::TOO_MANY_LOGIN_ATTEMPTS, - "登录尝试过多,请稍后重试", + "登录尝试过多", ); const RATE_LIMITED: AdminErrorSpec = AdminErrorSpec::new( StatusCode::TOO_MANY_REQUESTS, AdminErrorCode::RATE_LIMITED, - "请求过于频繁,请稍后重试", + "请求过于频繁", ); const INTERNAL: AdminErrorSpec = AdminErrorSpec::new( StatusCode::INTERNAL_SERVER_ERROR, diff --git a/backend/crates/gateway-api/tests/admin/errors.rs b/backend/crates/gateway-api/tests/admin/errors.rs index 5c208a19e..9e0451b01 100644 --- a/backend/crates/gateway-api/tests/admin/errors.rs +++ b/backend/crates/gateway-api/tests/admin/errors.rs @@ -513,6 +513,12 @@ mod provider { (Kind::Unsupported, 400, 40001, "该服务商不支持此操作"), (Kind::BadGateway, 502, 50201, "上游服务请求失败"), (Kind::Unavailable, 503, 50301, "服务商暂不可用"), + ( + Kind::CredentialRefreshRequired, + 503, + 50301, + "账号凭据需要刷新", + ), ( Kind::Ambiguous, 502, diff --git a/backend/crates/gateway-api/tests/admin/wire.rs b/backend/crates/gateway-api/tests/admin/wire.rs index 89d8e0e5a..1d02cdc1a 100644 --- a/backend/crates/gateway-api/tests/admin/wire.rs +++ b/backend/crates/gateway-api/tests/admin/wire.rs @@ -198,7 +198,7 @@ mod response { response_json(generic).await, json!({ "code": 42902, - "message": "请求过于频繁,请稍后重试", + "message": "请求过于频繁", "data": null }) ); @@ -212,7 +212,7 @@ mod response { response_json(login).await, json!({ "code": 42901, - "message": "登录尝试过多,请稍后重试", + "message": "登录尝试过多", "data": null }) ); diff --git a/backend/crates/gateway-store/src/postgres/account_groups.rs b/backend/crates/gateway-store/src/postgres/account_groups.rs index abf76a3aa..2e796cbcb 100644 --- a/backend/crates/gateway-store/src/postgres/account_groups.rs +++ b/backend/crates/gateway-store/src/postgres/account_groups.rs @@ -454,7 +454,10 @@ impl AccountGroupStore for PgAccountGroupRepository { .await .map_err(|source| unavailable("check account group delete conflict", source))?; if exists { - Err(conflict(command.id.as_str())) + Err(conflict( + command.id.as_str(), + ConflictKind::InvalidTransition, + )) } else { Err(not_found_store(command.id.as_str())) } @@ -681,11 +684,15 @@ fn require_one(rows: u64, id: &str) -> StoreResult<()> { } fn map_group_write_error(error: sqlx::Error, id: &str) -> StoreError { - if error - .as_database_error() - .is_some_and(|database| database.is_unique_violation()) + if let Some(database) = error.as_database_error() + && database.is_unique_violation() { - conflict(id) + let kind = if database.constraint() == Some("account_groups_name_uq") { + ConflictKind::DuplicateName + } else { + ConflictKind::InvalidTransition + }; + conflict(id, kind) } else { unavailable("write account group", error) } @@ -703,12 +710,12 @@ fn not_found_store(id: &str) -> StoreError { } } -fn conflict(id: &str) -> StoreError { +fn conflict(id: &str, kind: ConflictKind) -> StoreError { StoreError::Conflict { source: None, entity: ENTITY, id: id.to_owned(), - kind: ConflictKind::InvalidTransition, + kind, } } diff --git a/backend/crates/providers/openai/src/provider/failure.rs b/backend/crates/providers/openai/src/provider/failure.rs index d4f5aec0e..0c8e86613 100644 --- a/backend/crates/providers/openai/src/provider/failure.rs +++ b/backend/crates/providers/openai/src/provider/failure.rs @@ -1500,15 +1500,12 @@ pub(super) fn map_upstream_failure( .status .is_some_and(|status| status.is_client_error()) && is_cyber_policy_code(failure.code.as_deref()); - let continuation_failure = failure - .upstream_code() - .filter(|code| is_history_failure_code(code)) - .map(|_| ContinuationFailure::HistoryUnavailable); + let continuation_summary = failure.upstream_code().and_then(history_failure_summary); let send_state = upstream_send_state(failure.send_phase); - let error_kind = if continuation_failure.is_some() { - ProviderErrorKind::ContinuationRecoveryRequired + let (error_kind, summary) = if let Some(summary) = continuation_summary { + (ProviderErrorKind::ContinuationRecoveryRequired, summary) } else { - provider_error_kind(category) + upstream_failure_summary(category, failure.upstream_code()) }; let mut error = provider_error(error_kind, send_state) .with_upstream_failure_fields(failure.upstream_fields.clone()); @@ -1517,7 +1514,7 @@ pub(super) fn map_upstream_failure( let upgrade_required = failure.send_phase == CodexUpstreamSendPhase::BeforePayload && failure.status == Some(reqwest::StatusCode::UPGRADE_REQUIRED); if category == CodexFailureCategory::FlexUnavailable - || (!replay_safe && continuation_failure.is_none() && !upgrade_required) + || (!replay_safe && continuation_summary.is_none() && !upgrade_required) { error = error.with_retry_prohibited(); } @@ -1552,9 +1549,9 @@ pub(super) fn map_upstream_failure( if replay_boundary.permits_provider_proof() && replay_safe { error = error.with_replay_safe(); } - if let Some(continuation_failure) = continuation_failure { + if continuation_summary.is_some() { error = error - .with_continuation_failure(continuation_failure) + .with_continuation_failure(ContinuationFailure::HistoryUnavailable) .with_continuation_recovery_disposition( ContinuationRecoveryDisposition::ClientReplayRequired, ) @@ -1595,16 +1592,13 @@ pub(super) fn map_upstream_failure( if let Some(request_id) = failure.request_id.as_deref() { error = error.with_upstream_request_id(OpaqueUpstreamValue::new(request_id.to_owned())); } - let status = error - .upstream_status() - .map_or_else(|| "none".to_owned(), |status| status.to_string()); - let kind = error.kind().as_str(); + let summary = if cyber_policy_failure { + "请求被上游安全策略拦截" + } else { + summary + }; error = error.with_diagnostic( - ProviderDiagnostic::new(format!( - "OpenAI upstream failure: kind={}, status={status}", - kind - )) - .with_classification("upstream", "upstream_rejected"), + ProviderDiagnostic::new(summary).with_classification("upstream", "upstream_rejected"), ); MappedProviderFailure { error, @@ -1633,38 +1627,80 @@ pub(super) fn is_cyber_policy_code(code: Option<&str>) -> bool { code.is_some_and(|code| code.trim().eq_ignore_ascii_case("cyber_policy")) } -pub(super) fn is_history_failure_code(code: &str) -> bool { - [ - "previous_response_not_found", - "invalid_encrypted_content", - "missing_tool_output", - "no_tool_output", - ] - .iter() - .any(|known| code.trim().eq_ignore_ascii_case(known)) +fn history_failure_summary(code: &str) -> Option<&'static str> { + let code = code.trim(); + if code.eq_ignore_ascii_case("previous_response_not_found") { + Some("上游找不到先前的响应") + } else if code.eq_ignore_ascii_case("invalid_encrypted_content") { + Some("上游拒绝了加密的历史内容") + } else if code.eq_ignore_ascii_case("missing_tool_output") + || code.eq_ignore_ascii_case("no_tool_output") + { + Some("对话历史缺少工具调用结果") + } else { + None + } } -pub(super) const fn provider_error_kind(category: CodexFailureCategory) -> ProviderErrorKind { +fn upstream_failure_summary( + category: CodexFailureCategory, + code: Option<&str>, +) -> (ProviderErrorKind, &'static str) { match category { - CodexFailureCategory::ModelUnsupported => ProviderErrorKind::Unsupported, - CodexFailureCategory::CredentialExpired => ProviderErrorKind::Unauthorized, - CodexFailureCategory::IdentityVerificationRequired | CodexFailureCategory::Banned => { - ProviderErrorKind::PermissionDenied + CodexFailureCategory::ModelUnsupported => { + (ProviderErrorKind::Unsupported, "上游账号不支持此模型") } - CodexFailureCategory::UsageLimitExhausted => ProviderErrorKind::QuotaExhausted, - CodexFailureCategory::RateLimited | CodexFailureCategory::TurnRateLimited => { - ProviderErrorKind::RateLimited + CodexFailureCategory::CredentialExpired => { + (ProviderErrorKind::Unauthorized, "上游账号凭据无效") } - CodexFailureCategory::QuotaExhausted => ProviderErrorKind::QuotaExhausted, - CodexFailureCategory::CloudflareChallenge - | CodexFailureCategory::CloudflarePathBlocked - | CodexFailureCategory::FlexUnavailable - | CodexFailureCategory::Unavailable => ProviderErrorKind::Unavailable, - CodexFailureCategory::CapacityUnavailable => ProviderErrorKind::UpstreamCapacityUnavailable, - CodexFailureCategory::InvalidRequest => ProviderErrorKind::InvalidRequest, - CodexFailureCategory::PermissionDenied => ProviderErrorKind::PermissionDenied, - CodexFailureCategory::Timeout => ProviderErrorKind::Timeout, - CodexFailureCategory::Transport => ProviderErrorKind::Transport, + CodexFailureCategory::IdentityVerificationRequired => { + (ProviderErrorKind::PermissionDenied, "上游账号需要验证身份") + } + CodexFailureCategory::Banned => (ProviderErrorKind::PermissionDenied, "上游账号已被停用"), + CodexFailureCategory::UsageLimitExhausted => ( + ProviderErrorKind::QuotaExhausted, + "当前用量窗口的额度已用完", + ), + CodexFailureCategory::QuotaExhausted => { + (ProviderErrorKind::QuotaExhausted, "上游账号额度已用完") + } + CodexFailureCategory::RateLimited => (ProviderErrorKind::RateLimited, "上游请求频率受限"), + CodexFailureCategory::TurnRateLimited => { + (ProviderErrorKind::RateLimited, "当前对话轮次受到限流") + } + CodexFailureCategory::CloudflareChallenge => { + (ProviderErrorKind::Unavailable, "Cloudflare 要求验证请求") + } + CodexFailureCategory::CloudflarePathBlocked => { + (ProviderErrorKind::Unavailable, "上游接口返回空的 404 响应") + } + CodexFailureCategory::FlexUnavailable => { + (ProviderErrorKind::Unavailable, "Flex 服务容量不足") + } + CodexFailureCategory::CapacityUnavailable => ( + ProviderErrorKind::UpstreamCapacityUnavailable, + "上游模型容量不足", + ), + CodexFailureCategory::InvalidRequest => { + let summary = match code.map(str::trim) { + Some(code) if code.eq_ignore_ascii_case("unsupported_value") => { + "上游不支持该参数值" + } + Some(code) if code.eq_ignore_ascii_case("invalid_prompt") => "上游拒绝了提示词", + Some(code) if code.eq_ignore_ascii_case("context_length_exceeded") => { + "输入超出模型上下文长度" + } + _ => "上游拒绝了请求参数", + }; + (ProviderErrorKind::InvalidRequest, summary) + } + CodexFailureCategory::PermissionDenied => ( + ProviderErrorKind::PermissionDenied, + "上游账号无权执行此请求", + ), + CodexFailureCategory::Timeout => (ProviderErrorKind::Timeout, "上游响应超时"), + CodexFailureCategory::Unavailable => (ProviderErrorKind::Unavailable, "上游服务暂不可用"), + CodexFailureCategory::Transport => (ProviderErrorKind::Transport, "上游返回了非预期响应"), } } diff --git a/backend/crates/providers/openai/tests/provider/contract/error_details.rs b/backend/crates/providers/openai/tests/provider/contract/error_details.rs index d9f23538a..dade68a93 100644 --- a/backend/crates/providers/openai/tests/provider/contract/error_details.rs +++ b/backend/crates/providers/openai/tests/provider/contract/error_details.rs @@ -128,6 +128,9 @@ async fn upstream_codes_survive_http_and_websocket_opening_without_normalization body, ); let diagnostic = error.diagnostic().expect("safe diagnostic"); + if expected_kind == ProviderErrorKind::ContinuationRecoveryRequired { + assert_eq!(diagnostic.as_str(), "上游找不到先前的响应"); + } assert!(!diagnostic.as_str().contains(original_code)); assert!(!diagnostic.as_str().contains("PRIVATE_UPSTREAM_DETAIL")); assert!(!format!("{error:?} {error}").contains(original_code)); diff --git a/backend/crates/providers/openai/tests/provider/contract/mod.rs b/backend/crates/providers/openai/tests/provider/contract/mod.rs index 3d0a05c78..63c3b2583 100644 --- a/backend/crates/providers/openai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/openai/tests/provider/contract/mod.rs @@ -8875,6 +8875,7 @@ async fn capacity_http_and_websocket_opening_rejections_use_bounded_business_ret } }; assert_eq!(error.kind(), ProviderErrorKind::UpstreamCapacityUnavailable); + assert_eq!(error.diagnostic().unwrap().as_str(), "上游模型容量不足"); assert_eq!(error.upstream_status(), Some(status)); assert!(error.replay_is_safe()); assert_eq!(error.retry_after(), Some(Duration::from_secs(129600))); diff --git a/backend/crates/providers/xai/src/provider/failure.rs b/backend/crates/providers/xai/src/provider/failure.rs index 7db1d1665..32f25ce9e 100644 --- a/backend/crates/providers/xai/src/provider/failure.rs +++ b/backend/crates/providers/xai/src/provider/failure.rs @@ -525,24 +525,7 @@ pub(super) fn map_transport_error_with_state( allow_explicit_replay: bool, ) -> ProviderError { let transport_kind = error.kind(); - let kind = match transport_kind { - GrokInferenceTransportErrorKind::InvalidRequest => ProviderErrorKind::InvalidRequest, - GrokInferenceTransportErrorKind::Unsupported => ProviderErrorKind::Unsupported, - GrokInferenceTransportErrorKind::Unauthorized => ProviderErrorKind::Unauthorized, - GrokInferenceTransportErrorKind::PermissionDenied - | GrokInferenceTransportErrorKind::ModelAccessDenied - | GrokInferenceTransportErrorKind::PaymentRequired - | GrokInferenceTransportErrorKind::SafetyRejected => ProviderErrorKind::PermissionDenied, - GrokInferenceTransportErrorKind::RateLimited => ProviderErrorKind::RateLimited, - GrokInferenceTransportErrorKind::QuotaExhausted - | GrokInferenceTransportErrorKind::FreeQuotaExhausted - | GrokInferenceTransportErrorKind::ModelQuotaExhausted => ProviderErrorKind::QuotaExhausted, - GrokInferenceTransportErrorKind::Timeout => ProviderErrorKind::Timeout, - GrokInferenceTransportErrorKind::Transport => ProviderErrorKind::Transport, - GrokInferenceTransportErrorKind::Protocol => ProviderErrorKind::Protocol, - GrokInferenceTransportErrorKind::Unavailable => ProviderErrorKind::Unavailable, - GrokInferenceTransportErrorKind::Cancelled => ProviderErrorKind::Cancelled, - }; + let kind = transport_kind.provider_kind(); let mut mapped = provider_error( kind, forced_send_state.unwrap_or_else(|| error.send_state()), @@ -579,14 +562,8 @@ pub(super) fn map_transport_error_with_state( mapped = mapped.with_client_visible_upstream_error(detail); } let diagnostic = error.diagnostic().cloned().unwrap_or_else(|| { - let status = error - .status() - .map_or_else(|| "none".to_owned(), |value| value.to_string()); - ProviderDiagnostic::new(format!( - "xAI upstream failure: kind={}, status={status}", - kind.as_str() - )) - .with_classification("upstream", "upstream_failure") + ProviderDiagnostic::new(transport_kind.diagnostic_message()) + .with_classification("upstream", "upstream_failure") }); mapped = mapped.with_diagnostic(diagnostic); if error.requires_credential_recovery() { diff --git a/backend/crates/providers/xai/src/transport/canonical.rs b/backend/crates/providers/xai/src/transport/canonical.rs index 76c415be5..13dc4df58 100644 --- a/backend/crates/providers/xai/src/transport/canonical.rs +++ b/backend/crates/providers/xai/src/transport/canonical.rs @@ -4,7 +4,8 @@ use std::collections::{BTreeMap, BTreeSet}; use gateway_core::engine::provider::NativeResponseTranslator; use gateway_core::error::{ - ClientVisibleUpstreamError, OpaqueUpstreamValue, ProviderError, ProviderErrorKind, + ClientVisibleUpstreamError, OpaqueUpstreamValue, ProviderDiagnostic, ProviderError, + ProviderErrorKind, }; use gateway_core::event::{ ContentItem, ContentKind, FinishReason, GatewayEvent, ProtocolWireEvent, ProviderEvent, @@ -20,6 +21,7 @@ use gateway_protocol::openai::events::{TokenUsage, billable_usage_is_complete, e use gateway_protocol::openai::sse::{SseEvent, SseEventDecoder}; use serde_json::Value; +use super::GrokInferenceTransportErrorKind; use super::request::{GrokResponseTransform, GrokResponsesRequest}; use super::upstream_error::{classify_grok_quota_failure, scrub_account_fingerprints}; @@ -1207,19 +1209,24 @@ fn upstream_event_error(value: &Value) -> ProviderError { .or_else(|| value.pointer("/response/error/type")) .and_then(Value::as_str); let message = upstream_error_field(value, "message"); - let kind = if classify_grok_quota_failure(code, error_type, message).is_some() { - ProviderErrorKind::QuotaExhausted + let kind = if let Some(quota) = classify_grok_quota_failure(code, error_type, message) { + GrokInferenceTransportErrorKind::from_quota(quota) } else { match code { - Some("invalid_request" | "invalid_prompt") => ProviderErrorKind::InvalidRequest, - Some("unsupported" | "unsupported_feature") => ProviderErrorKind::Unsupported, - Some("unauthorized" | "invalid_token") => ProviderErrorKind::Unauthorized, - Some("permission_denied") => ProviderErrorKind::PermissionDenied, - Some("rate_limit_exceeded") => ProviderErrorKind::RateLimited, - _ => ProviderErrorKind::Unavailable, + Some("invalid_request" | "invalid_prompt") => { + GrokInferenceTransportErrorKind::InvalidRequest + } + Some("unsupported" | "unsupported_feature") => { + GrokInferenceTransportErrorKind::Unsupported + } + Some("unauthorized" | "invalid_token") => GrokInferenceTransportErrorKind::Unauthorized, + Some("permission_denied") => GrokInferenceTransportErrorKind::PermissionDenied, + Some("rate_limit_exceeded") => GrokInferenceTransportErrorKind::RateLimited, + _ => GrokInferenceTransportErrorKind::Unavailable, } }; - let mut error = ProviderError::new(kind, UpstreamSendState::Sent) + let mut error = ProviderError::new(kind.provider_kind(), UpstreamSendState::Sent) + .with_diagnostic(ProviderDiagnostic::new(kind.diagnostic_message())) .with_raw_upstream_error(gateway_core::error::RawUpstreamError::new( value.to_string(), )) diff --git a/backend/crates/providers/xai/src/transport/inference.rs b/backend/crates/providers/xai/src/transport/inference.rs index 752034d5d..6a916b5fc 100644 --- a/backend/crates/providers/xai/src/transport/inference.rs +++ b/backend/crates/providers/xai/src/transport/inference.rs @@ -9,13 +9,14 @@ use futures::Stream; use gateway_core::engine::middleware::MiddlewareHeader; use gateway_core::error::{ ClientVisibleUpstreamError, ErrorSource, OpaqueUpstreamValue, ProviderDiagnostic, - RawUpstreamError, + ProviderErrorKind, RawUpstreamError, }; use gateway_core::event::UpstreamHttpVersion; use gateway_core::upstream::UpstreamSendState; use url::Url; use zeroize::Zeroizing; +use super::upstream_error::GrokQuotaFailureKind; use super::{GrokHeader, GrokSessionBinding}; /// 交给注入的 HTTP SSE transport 的自持有请求 @@ -352,6 +353,58 @@ pub enum GrokInferenceTransportErrorKind { Cancelled, } +impl GrokInferenceTransportErrorKind { + pub(crate) const fn from_quota(failure: GrokQuotaFailureKind) -> Self { + match failure { + GrokQuotaFailureKind::Account => Self::QuotaExhausted, + GrokQuotaFailureKind::FreeAccount => Self::FreeQuotaExhausted, + GrokQuotaFailureKind::FreeModelUsage => Self::ModelQuotaExhausted, + } + } + + pub(crate) const fn provider_kind(self) -> ProviderErrorKind { + match self { + Self::InvalidRequest => ProviderErrorKind::InvalidRequest, + Self::Unsupported => ProviderErrorKind::Unsupported, + Self::Unauthorized => ProviderErrorKind::Unauthorized, + Self::PermissionDenied + | Self::ModelAccessDenied + | Self::PaymentRequired + | Self::SafetyRejected => ProviderErrorKind::PermissionDenied, + Self::RateLimited => ProviderErrorKind::RateLimited, + Self::QuotaExhausted | Self::FreeQuotaExhausted | Self::ModelQuotaExhausted => { + ProviderErrorKind::QuotaExhausted + } + Self::Timeout => ProviderErrorKind::Timeout, + Self::Transport => ProviderErrorKind::Transport, + Self::Protocol => ProviderErrorKind::Protocol, + Self::Unavailable => ProviderErrorKind::Unavailable, + Self::Cancelled => ProviderErrorKind::Cancelled, + } + } + + pub(crate) const fn diagnostic_message(self) -> &'static str { + match self { + Self::InvalidRequest => "上游拒绝了请求参数", + Self::Unsupported => "上游不支持此请求", + Self::Unauthorized => "上游账号凭据无效", + Self::PermissionDenied => "上游账号无权执行此请求", + Self::ModelAccessDenied => "上游账号无权使用此模型", + Self::PaymentRequired => "上游要求付费", + Self::SafetyRejected => "请求被上游安全策略拦截", + Self::RateLimited => "上游请求频率受限", + Self::QuotaExhausted => "上游账号额度已用完", + Self::FreeQuotaExhausted => "上游账号免费额度已用完", + Self::ModelQuotaExhausted => "此模型的免费额度已用完", + Self::Timeout => "上游响应超时", + Self::Transport => "上游连接失败", + Self::Protocol => "上游协议处理失败", + Self::Unavailable => "上游服务暂不可用", + Self::Cancelled => "请求已取消", + } + } +} + /// 推理 transport 失败,公开分类与受控上游详情分别承载 #[derive(Clone)] pub struct GrokInferenceTransportError { diff --git a/backend/crates/providers/xai/src/transport/network.rs b/backend/crates/providers/xai/src/transport/network.rs index 8a8195c32..bfb3d6fd5 100644 --- a/backend/crates/providers/xai/src/transport/network.rs +++ b/backend/crates/providers/xai/src/transport/network.rs @@ -1156,18 +1156,28 @@ async fn classify_inference_status( if let Some(raw) = raw { error = error.with_raw_upstream_error(raw); } - let diagnostic_code = if status == StatusCode::BAD_REQUEST && reasoning_decode_failed(&metadata) + let (code, message) = if status == StatusCode::BAD_REQUEST && reasoning_decode_failed(&metadata) { - "reasoning_decode_failed" + ("reasoning_decode_failed", "上游无法解码加密的推理内容") } else { - body_failure.map_or("upstream_failure", GrokBodyFailure::marker) + let message = match (body_failure, kind) { + ( + Some(GrokBodyFailure::ModelCapacity), + GrokInferenceTransportErrorKind::RateLimited, + ) => "上游模型容量不足", + ( + Some(GrokBodyFailure::EmptyUpstream), + GrokInferenceTransportErrorKind::Unavailable, + ) => "上游未返回模型响应", + _ => kind.diagnostic_message(), + }; + ( + body_failure.map_or("upstream_failure", GrokBodyFailure::marker), + message, + ) }; - error = error.with_diagnostic( - ProviderDiagnostic::new(format!( - "xAI upstream rejected request: status={status_code}" - )) - .with_classification("upstream", diagnostic_code), - ); + error = error + .with_diagnostic(ProviderDiagnostic::new(message).with_classification("upstream", code)); error = error.with_upstream_failure_fields(gateway_core::upstream::UpstreamFailureFields { status: Some(status_code), code: metadata.original_code, @@ -1221,7 +1231,7 @@ enum GrokBodyFailure { impl GrokBodyFailure { fn transport_kind(self) -> GrokInferenceTransportErrorKind { match self { - Self::Quota(failure) => quota_transport_error_kind(failure), + Self::Quota(failure) => GrokInferenceTransportErrorKind::from_quota(failure), Self::Billing => GrokInferenceTransportErrorKind::PaymentRequired, Self::EmptyUpstream => GrokInferenceTransportErrorKind::Unavailable, Self::ModelCapacity | Self::RateLimit => GrokInferenceTransportErrorKind::RateLimited, @@ -1372,7 +1382,7 @@ fn first_string(object: &serde_json::Map, fields: &[&str]) -> Opt fn classify_payment_required(metadata: &InferenceErrorMetadata) -> GrokInferenceTransportErrorKind { quota_failure(metadata).map_or( GrokInferenceTransportErrorKind::PaymentRequired, - quota_transport_error_kind, + GrokInferenceTransportErrorKind::from_quota, ) } @@ -1392,7 +1402,7 @@ fn classify_forbidden( } else if let Some(failure) = body_failure { failure.transport_kind() } else if let Some(failure) = quota_failure(metadata) { - quota_transport_error_kind(failure) + GrokInferenceTransportErrorKind::from_quota(failure) } else if model_access_denied(metadata) { GrokInferenceTransportErrorKind::ModelAccessDenied } else { @@ -1405,7 +1415,7 @@ fn classify_too_many_requests( ) -> GrokInferenceTransportErrorKind { quota_failure(metadata).map_or( GrokInferenceTransportErrorKind::RateLimited, - quota_transport_error_kind, + GrokInferenceTransportErrorKind::from_quota, ) } @@ -1441,16 +1451,6 @@ fn quota_failure(metadata: &InferenceErrorMetadata) -> Option GrokInferenceTransportErrorKind { - match failure { - GrokQuotaFailureKind::Account => GrokInferenceTransportErrorKind::QuotaExhausted, - GrokQuotaFailureKind::FreeAccount => GrokInferenceTransportErrorKind::FreeQuotaExhausted, - GrokQuotaFailureKind::FreeModelUsage => { - GrokInferenceTransportErrorKind::ModelQuotaExhausted - } - } -} - fn model_access_denied(metadata: &InferenceErrorMetadata) -> bool { metadata.message.as_deref().is_some_and(|message| { let message = message.to_ascii_lowercase(); diff --git a/backend/crates/providers/xai/tests/transport/canonical.rs b/backend/crates/providers/xai/tests/transport/canonical.rs index 8a6c6c2b2..5b5057f97 100644 --- a/backend/crates/providers/xai/tests/transport/canonical.rs +++ b/backend/crates/providers/xai/tests/transport/canonical.rs @@ -1604,6 +1604,10 @@ fn decoder_should_classify_free_quota_failed_event() { .push(body.as_bytes()) .expect_err("free quota failure must surface"); + assert_eq!( + error.diagnostic().unwrap().as_str(), + "上游账号免费额度已用完" + ); assert_eq!( error.kind(), gateway_core::error::ProviderErrorKind::QuotaExhausted diff --git a/backend/crates/providers/xai/tests/transport/network.rs b/backend/crates/providers/xai/tests/transport/network.rs index 61ce4c58e..9ba107afc 100644 --- a/backend/crates/providers/xai/tests/transport/network.rs +++ b/backend/crates/providers/xai/tests/transport/network.rs @@ -918,6 +918,10 @@ async fn inference_transport_should_classify_free_usage_429_as_account_free_quot error.kind(), GrokInferenceTransportErrorKind::FreeQuotaExhausted ); + assert_eq!( + error.diagnostic().unwrap().as_str(), + "上游账号免费额度已用完" + ); assert_eq!(error.status(), Some(429)); assert_eq!( error.upstream_code().map(|code| code.as_str()), diff --git a/docs/api.md b/docs/api.md index b07d3153a..876f55e07 100644 --- a/docs/api.md +++ b/docs/api.md @@ -2796,7 +2796,7 @@ Dashboard 返回原始 `asOf` 及 `asOfDisplay`,作为当前数据的查询锚 省略时包含全部来源。筛选与列表、详情共用下述来源规则,并在统计总数和分页前与其他明细条件一同生效。 其他状态携带 `errorOrigin` 或来源值无效时返回 `400` -请求列表的 `errorCode` / `errorMessage` 提供最终请求的错误码与错误信息,未记录时为 `null`。 +请求列表的 `errorCode` 保留已记录的错误码,`errorMessage` 是最终失败的安全摘要,例如账号额度耗尽或模型容量不足。两者各自缺失时为 `null`。 `clientStatusCode` / `upstreamStatusCode` 分别提供已记录的客户端与上游状态码,未记录时为 `null`。 HTTP SSE 请求可能在返回 HTTP 200 后流内失败;WebSocket 已升级时,客户端错误状态码不代表 HTTP 握手状态或 WebSocket 关闭码。 两侧状态码不互相替代,也不覆盖 `logicalOutcome` diff --git a/frontend/src/api/request/plugins/error.ts b/frontend/src/api/request/plugins/error.ts index ad00c2ad4..6cf304d39 100644 --- a/frontend/src/api/request/plugins/error.ts +++ b/frontend/src/api/request/plugins/error.ts @@ -123,7 +123,7 @@ function responseHeader( : undefined } -function httpFallback(status: number) { +export function httpFallback(status: number) { switch (status) { case 400: return t('common.errors.invalidParameters') diff --git a/frontend/src/api/request/plugins/raw.ts b/frontend/src/api/request/plugins/raw.ts index 2ad958998..c78807e3f 100644 --- a/frontend/src/api/request/plugins/raw.ts +++ b/frontend/src/api/request/plugins/raw.ts @@ -1,6 +1,6 @@ import type { RawResponse, RawResponseMeta, RequestContext, RequestNext } from '../types' import { t } from '@/i18n' -import { ApiError, normalizeApiResponseError } from './error' +import { ApiError, httpFallback, normalizeApiResponseError } from './error' export async function rawPlugin(context: RequestContext, next: RequestNext) { const options = context.raw @@ -54,7 +54,7 @@ export async function rawPlugin(context: RequestContext, next: RequestNext) { throw normalized throw new ApiError( response.status >= 400 - ? t('common.errors.http', { status: response.status }) + ? httpFallback(response.status) : t('common.errors.unsupportedResponse'), response.status, undefined, diff --git a/frontend/src/components/usage/UsageErrorCell.vue b/frontend/src/components/usage/UsageErrorCell.vue index 2327e620b..426e1f103 100644 --- a/frontend/src/components/usage/UsageErrorCell.vue +++ b/frontend/src/components/usage/UsageErrorCell.vue @@ -18,13 +18,13 @@ const { t } = useI18n({ useScope: 'global' }) const message = computed(() => props.record.errorMessage?.replace(/^OpenAI upstream failure: /, '')) const code = computed(() => usageErrorCode(props.record) || props.record.errorKind) const origin = computed(() => usageErrorOrigin(props.record)) -const description = computed(() => [code.value, message.value].filter(Boolean).join(' · ') || t('usage.error.noDetails')) const outcome = computed(() => usageErrorTitle(props.record)) +const summary = computed(() => message.value || code.value || t('usage.error.noDetails')) diff --git a/frontend/src/i18n/locales/en/common.json b/frontend/src/i18n/locales/en/common.json index 608feee17..e87bc81e3 100644 --- a/frontend/src/i18n/locales/en/common.json +++ b/frontend/src/i18n/locales/en/common.json @@ -3,16 +3,16 @@ "errors": { "canceled": "Request canceled", "timeout": "Request timed out", - "network": "Connection failed, check your network", + "network": "Could not connect to the service", "invalidParameters": "Invalid request parameters", "signInRequired": "Sign-in required", "forbidden": "You do not have permission to perform this action", "notFound": "Endpoint not found", - "conflict": "Resource conflict, refresh and try again", + "conflict": "The resource state prevents this action", "payloadTooLarge": "Request payload is too large", "unsupportedFormat": "Unsupported request format", "invalidContent": "Invalid request content", - "rateLimited": "Too many requests, try again later", + "rateLimited": "Too many requests", "internal": "Internal server error", "upstreamFailure": "Upstream service request failed", "unavailable": "Service temporarily unavailable", @@ -29,7 +29,7 @@ "invalidTimeRange": "Invalid time range", "invalidCredentials": "Invalid sign-in credentials", "invalidAdminApiKey": "Invalid admin API key", - "tooManyLoginAttempts": "Too many sign-in attempts, try again later", + "tooManyLoginAttempts": "Too many sign-in attempts", "upstreamResultUnknown": "Upstream result unknown, refresh the status before deciding whether to retry" }, "status": { diff --git a/frontend/src/i18n/locales/zh-Hans/common.json b/frontend/src/i18n/locales/zh-Hans/common.json index d96a374ad..5a6cf0ffd 100644 --- a/frontend/src/i18n/locales/zh-Hans/common.json +++ b/frontend/src/i18n/locales/zh-Hans/common.json @@ -3,16 +3,16 @@ "errors": { "canceled": "请求已取消", "timeout": "请求超时", - "network": "网络连接失败,请检查网络", + "network": "无法连接到服务", "invalidParameters": "请求参数不合法", "signInRequired": "需要登录", "forbidden": "没有权限执行此操作", "notFound": "请求的接口不存在", - "conflict": "资源状态冲突,请刷新后重试", + "conflict": "当前资源状态不允许此操作", "payloadTooLarge": "请求内容过大", "unsupportedFormat": "请求格式不受支持", "invalidContent": "请求内容不合法", - "rateLimited": "请求过于频繁,请稍后重试", + "rateLimited": "请求过于频繁", "internal": "服务内部错误", "upstreamFailure": "上游服务请求失败", "unavailable": "服务暂不可用", @@ -28,8 +28,8 @@ "malformedJson": "请求体不是合法 JSON", "invalidTimeRange": "时间范围不合法", "invalidCredentials": "登录凭据错误", - "invalidAdminApiKey": "管理 API密钥无效", - "tooManyLoginAttempts": "登录尝试过多,请稍后重试", + "invalidAdminApiKey": "管理 API Key 无效", + "tooManyLoginAttempts": "登录尝试过多", "upstreamResultUnknown": "上游结果未知,请刷新状态再决定是否重试" }, "status": { diff --git a/frontend/src/i18n/locales/zh-Hant/common.json b/frontend/src/i18n/locales/zh-Hant/common.json index 6c05092b0..4bb4a541d 100644 --- a/frontend/src/i18n/locales/zh-Hant/common.json +++ b/frontend/src/i18n/locales/zh-Hant/common.json @@ -3,16 +3,16 @@ "errors": { "canceled": "請求已取消", "timeout": "請求超時", - "network": "網絡連接失敗,請檢查網絡", + "network": "無法連接到服務", "invalidParameters": "請求參數不合法", "signInRequired": "需要登錄", "forbidden": "沒有權限執行此操作", "notFound": "請求的接口不存在", - "conflict": "資源狀態衝突,請刷新後重試", + "conflict": "當前資源狀態不允許此操作", "payloadTooLarge": "請求內容過大", "unsupportedFormat": "請求格式不受支持", "invalidContent": "請求內容不合法", - "rateLimited": "請求過於頻繁,請稍後重試", + "rateLimited": "請求過於頻繁", "internal": "服務內部錯誤", "upstreamFailure": "上游服務請求失敗", "unavailable": "服務暫不可用", @@ -28,8 +28,8 @@ "malformedJson": "請求體不是合法 JSON", "invalidTimeRange": "時間範圍不合法", "invalidCredentials": "登錄憑據錯誤", - "invalidAdminApiKey": "管理 API密鑰無效", - "tooManyLoginAttempts": "登錄嘗試過多,請稍後重試", + "invalidAdminApiKey": "管理 API Key 無效", + "tooManyLoginAttempts": "登錄嘗試過多", "upstreamResultUnknown": "上游結果未知,請刷新狀態再決定是否重試" }, "status": { diff --git a/frontend/src/views/accounts/composables/useAccountEditor.ts b/frontend/src/views/accounts/composables/useAccountEditor.ts index 94e367eae..2ea57914c 100644 --- a/frontend/src/views/accounts/composables/useAccountEditor.ts +++ b/frontend/src/views/accounts/composables/useAccountEditor.ts @@ -6,6 +6,7 @@ import { useAsyncAction } from '@/composables/useAsyncAction' import { useRequestState } from '@/composables/useRequestState' import { t } from '@/i18n' import { notification as ZNotification } from '@/utils/notification' +import { errorMessage } from '@/utils/operation' import { accountNameUpdate } from '../utils/accountName' import { accountSchedulingValues, concurrencyLimitInput } from '../utils/schedulingForm' import { emptyApiKeyAccountForm, isOpenAiApiKeyAccount, isOpenAiOAuthAccount, parseApiKeyConfiguration } from '../utils/upstreamApiKey' @@ -29,8 +30,8 @@ export function useAccountEditor(options: { const saveAction = useAsyncAction() const saving = saveAction.loading const apiKey = ref(emptyApiKeyAccountForm()) - const configurationRequest = useRequestState(() => ZNotification.error({ - message: t('accounts.editor.loadError'), + const configurationRequest = useRequestState(cause => ZNotification.error({ + message: errorMessage(cause, t('accounts.editor.loadError')), })) const savedConfiguration = shallowRef() const oauthTransport = shallowRef('')