# 错误处理规范 > 更新时间:2026-06-22 > 适用范围:HXOPS 前后端 API 与 UI 错误反馈 > 读者:组内同事、AI 编程助手 > 文档定位:**错误契约、分层职责与禁止项**的权威说明。`AGENTS.md` §8 仅保留强约束摘要,细则以本文为准。 --- ## 1. 统一错误契约 前后端 JSON API 采用 **Envelope** 结构(由 `ENABLE_API_ENVELOPE` 与全局 handler 保证)。 **成功:** ```json { "success": true, "data": { }, "request_id": "req_abc123", "timestamp": "2026-06-22T08:00:00Z" } ``` **失败:** ```json { "success": false, "error": { "code": "USER.EMAIL_EXISTS", "message": "Email already exists", "details": { "field": "email" }, "retryable": false }, "request_id": "req_abc123", "timestamp": "2026-06-22T08:00:00Z" } ``` | 字段 | 说明 | |------|------| | `error.code` | 机器可读错误码,格式 `DOMAIN.SUBTYPE`(如 `AUTH.UNAUTHORIZED`) | | `error.message` | 英文或简短说明,供日志与 fallback;**前端优先用 i18n 映射** | | `error.details` | 可选结构化信息(字段名、冲突项等),供前端分支逻辑 | | `error.retryable` | 是否建议用户重试(503 等) | | `request_id` | 与 `X-Request-Id` 对齐,便于排障 | --- ## 2. 后端规范 ### 2.1 分层职责 | 层 | 职责 | |----|------| | **Route(`api/`)** | 参数读取、权限装饰器、调用 service;**不**手写 `jsonify({"error": ...})` | | **Service(`services/`)** | 业务校验失败 `raise AppError` 子类;不构造 HTTP Response | | **全局 handler(`app/__init__.py`)** | 捕获 `AppError` / `HTTPException` / 未预期异常 → `error_payload` | ### 2.2 使用 `app/errors.py` 优先使用已有子类,语义不明确时再 `raise AppError(...)`: | 异常 | 典型 HTTP | 默认 code | |------|-----------|-----------| | `ValidationError` | 400 | `VALIDATION.INVALID_PARAM` | | `UnauthorizedError` | 401 | `AUTH.UNAUTHORIZED` | | `ForbiddenError` | 403 | `AUTH.FORBIDDEN` | | `NotFoundError` | 404 | `RESOURCE.NOT_FOUND` | | `ConflictError` | 409 | `RESOURCE.CONFLICT`(可自定义 code) | | `ServiceUnavailableError` | 503 | `SYSTEM.SERVICE_UNAVAILABLE` | **示例(service / route):** ```python from app.errors import ValidationError, NotFoundError, ConflictError if not name: raise ValidationError("Name is required") if not row: raise NotFoundError("Agent not found") if email_exists: raise ConflictError("Email already exists", code="USER.EMAIL_EXISTS", details={"field": "email"}) ``` **成功响应:** 使用 `app.response_utils.ok(data)`,或在 envelope 开启时返回 plain dict(由 `@app.after_request` 包装)。 ### 2.3 错误码命名 - 格式:`<域>.<语义>`,全大写,点号分隔。 - 域示例:`AUTH`、`USER`、`RESOURCE`、`VALIDATION`、`KB`、`WECOM`、`SYSTEM`。 - **新增 code 必须同步前端四语言** `locales/*/errors.json` → `errors.codes.`(`.` 换 `_`)。 ### 2.4 禁止项(后端) | ❌ 不要 | ✅ 应该 | |---------|---------| | `return jsonify({"error": "Not found"}), 404` | `raise NotFoundError(...)` | | `return jsonify({"ok": False, "error": "..."}), 400` | `raise ValidationError(...)` | | 在 service 里 `return (jsonify(...), 4xx)` | `raise AppError` 交给 handler | | 500 时把堆栈/ SQL 返回给客户端 | 日志记录细节;客户端仅 `SYSTEM.INTERNAL_ERROR` | | 随意字符串作 code(`"not_found"`) | `RESOURCE.NOT_FOUND` 等规范 code | > 历史路由(如部分 `workspace_shipping_notice.py`)仍有 legacy `{"error": "..."}` 写法;**新接口与改动处须改为 `AppError`**,逐步收敛。 --- ## 3. 前端规范 ### 3.1 分层职责 | 层 | 职责 | |----|------| | **`shared/api/client.ts`** | 唯一 JSON 客户端:`requestJson` 解析 envelope,失败抛 `BusinessError`(含 `code` / `message` / `details` / `status` / `requestId`) | | **`features/*/api/*.api.ts`** | 只组装 URL 与 body,调用 `requestJson`;**不** catch 后改写成字符串 | | **Composables / Views** | catch `BusinessError`,用 `useMessage()` 或域内 resolver 展示;按 `status` / `code` 做分支(401 跳登录等) | | **Components** | 一般不 catch API;由父级注入错误状态或回调 | ### 3.2 `BusinessError` 与 i18n `requestJson` 抛出前已通过 `resolveLocalizedErrorMessage` 将 `error.code` 映射到 `errors.codes.*`(四语言 `errors.json`)。 **Composable 中展示错误(推荐):** ```typescript import { BusinessError } from '@/shared/api/client'; import { useMessage } from '@/shared/composables/useMessage'; const msg = useMessage(); try { await saveProfile(payload); msg.success(t('workspace.profile.msg.saved')); } catch (e) { const message = e instanceof BusinessError ? e.message : t('workspace.profile.msg.saveFailed'); msg.error(message); } ``` **按状态分支:** ```typescript catch (e) { if (e instanceof BusinessError && e.status === 401) { msg.error(t('login.loginRequired')); return; } if (e instanceof BusinessError && e.status === 403) { msg.error(e.message); return; } msg.error(e instanceof Error ? e.message : t('errors.generic')); } ``` **域内复杂映射**(如 Casdoor 登录):在 `shared/utils/` 或 feature `utils/` 提供 `resolveXxxErrorMessage(err: BusinessError, t)`,避免 View 内重复 if-else。 ### 3.3 表单校验 vs 服务端错误 | 类型 | 处理方式 | |------|----------| | 前端必填 / 格式 | 提交前校验,`msg.warning(t('...'))`,不发起请求 | | 服务端业务拒绝 | API 抛 `BusinessError`,展示 `e.message`(已 i18n) | | 字段级错误 | 读 `e.details.field`,高亮对应表单项 | ### 3.4 SSE / 流式对话 对话流式接口**不走** `requestJson`,错误处理在 `features/chat/composables/useChat.ts` 内完成(解析 SSE event、断线重试等)。勿用 Axios 替代。 ### 3.5 禁止项(前端) | ❌ 不要 | ✅ 应该 | |---------|---------| | 在组件里直接 `fetch('/api/...')` | `features/*/api/*.api.ts` + `requestJson` | | `(e as Error).message` 且不判断类型 | 优先 `instanceof BusinessError` | | catch 后静默吞掉(无 UI、无日志) | `msg.error` 或向上抛出 | | catch 里硬编码中文 | `e.message`(已映射)或 `t('errors....')` | | 在 `*.api.ts` 里 `msg.error` | API 层只抛错,UI 层负责展示 | | 新增后端 code 却不加 `errors.json` | 四语言同步 `errors.codes.*` | --- ## 4. 新增错误码检查清单 1. 后端:在 `app/errors.py` 选用或新增语义明确的 `code`。 2. 前端:在 `locales/{zh-CN,zh-TW,en,th}/errors.json` 的 `codes` 下增加键(`USER.EMAIL_EXISTS` → `USER_EMAIL_EXISTS`)。 3. 若需按 `details` 分支,在 composable 文档注释中说明字段约定。 4. 自测:触发该错误,确认四语言文案与 HTTP 状态码正确。 --- ## 5. 相关文件 | 文件 | 说明 | |------|------| | `backend/app/errors.py` | 业务异常类型 | | `backend/app/response_utils.py` | `ok()`、`error_payload()` | | `backend/app/__init__.py` | 全局 errorhandler、envelope 包装 | | `frontend/src/shared/api/client.ts` | `requestJson`、`BusinessError` | | `frontend/src/locales/*/errors.json` | 错误码 i18n | | `frontend/src/shared/composables/useMessage.ts` | 全局 error/success 弹窗 | --- ## 6. 相关文档 - [AGENTS.md](../../AGENTS.md) §8 — 红线摘要 - [frontend_architecture_refactor.md](../refactor/frontend_architecture_refactor.md) — 前端分层与 API 层约束