From a332ba58ba84880d4598b627a8af630ef38fbfa4 Mon Sep 17 00:00:00 2001 From: chengkai3 Date: Thu, 18 Jun 2026 10:19:25 +0800 Subject: [PATCH] =?UTF-8?q?[fix]:[FL-190][=E7=B3=BB=E7=BB=9F=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E4=B8=AD=E7=9A=84stacktrace=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E4=B8=8D=E8=A6=81=E7=9B=B4=E6=8E=A5=E5=B1=95=E7=A4=BA=E5=88=B0?= =?UTF-8?q?=E9=A1=B5=E9=9D=A2=E7=BB=99=E7=94=A8=E6=88=B7=E7=9C=8B]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 后端:在 exception_handlers.py 添加文档注释,明确说明 stacktrace 字段仅供开发调试使用 - 前端:在 api.ts 添加 ApiErrorResponse 类型定义和文档注释,明确 readApiError 函数只提取 detail 字段展示给用户 - stacktrace 在 debug 模式下会返回给浏览器(可在开发者工具中查看),但前端不会展示到页面上 Co-Authored-By: Claude Sonnet 4.6 Co-authored-by: multica-agent --- api/app/core/exception_handlers.py | 9 +++++++++ web/src/lib/api.ts | 22 +++++++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/api/app/core/exception_handlers.py b/api/app/core/exception_handlers.py index f069780..20c4d99 100644 --- a/api/app/core/exception_handlers.py +++ b/api/app/core/exception_handlers.py @@ -6,6 +6,14 @@ from .config import get_settings async def global_exception_handler(request: Request, exc: Exception) -> JSONResponse: + """ + 全局异常处理器 + + 返回的错误响应包含: + - detail: 错误描述信息(面向用户,前端会展示此字段) + - type: 异常类型名称 + - stacktrace: 调用栈信息(仅在debug模式下返回,仅供开发人员调试使用,前端不应展示给用户) + """ settings = get_settings() error_response = { @@ -13,6 +21,7 @@ async def global_exception_handler(request: Request, exc: Exception) -> JSONResp "type": type(exc).__name__, } + # stacktrace 仅用于开发调试,不应直接展示到页面给用户看 if settings.debug_mode: error_response["stacktrace"] = traceback.format_exc() diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index edff085..5ae436f 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -36,9 +36,29 @@ export function getApiBaseUrl(): string { export const API_BASE_URL = getApiBaseUrl(); +/** + * API 错误响应结构 + * + * 后端在异常时返回的完整错误响应包含: + * - detail: 错误描述信息(面向用户,应展示此字段) + * - type: 异常类型名称(供开发参考) + * - stacktrace: 调用栈信息(仅在debug模式下返回,仅供开发人员调试,不应展示给用户) + */ +interface ApiErrorResponse { + detail?: string; + type?: string; + stacktrace?: string; // 仅供开发调试,不展示给用户 +} + +/** + * 从 API 错误响应中提取用户友好的错误信息 + * + * 注意:此函数仅提取 detail 字段展示给用户, + * stacktrace 字段(如果存在)不会暴露到用户界面 + */ export async function readApiError(response: Response): Promise { try { - const data = (await response.json()) as { detail?: string }; + const data = (await response.json()) as ApiErrorResponse; return data.detail ?? `HTTP ${response.status}`; } catch { return `HTTP ${response.status}`;