From 463b731da392a5f5c4c8c94d61e349f36b8230fc Mon Sep 17 00:00:00 2001 From: zyc <1439655764@qq.com> Date: Fri, 30 Jan 2026 13:16:39 +0800 Subject: [PATCH] feat: integrate log center error reporting --- src/api/request.ts | 64 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/src/api/request.ts b/src/api/request.ts index 0e3fd61..5fcb8a2 100644 --- a/src/api/request.ts +++ b/src/api/request.ts @@ -7,6 +7,58 @@ const BASE_URL = import.meta.env.PROD ? (import.meta.env.VITE_API_BASE_URL || 'http://localhost:8001') : ''; // 开发环境使用相对路径,通过 Vite 代理 +// Log Center 配置 +const LOG_CENTER_URL = import.meta.env.VITE_LOG_CENTER_URL || 'https://qiyuan-log-center-api.airlabs.art'; +const LOG_CENTER_ENABLED = import.meta.env.VITE_LOG_CENTER_ENABLED !== 'false'; + +/** + * 上报错误到 Log Center + */ +function reportToLogCenter(error: Error, context?: Record) { + if (!LOG_CENTER_ENABLED) return; + + try { + // 解析堆栈信息 + const stackLines = error.stack?.split('\n') || []; + const match = stackLines[1]?.match(/at\s+.*\s+\((.+):(\d+):\d+\)/); + + const payload = { + project_id: 'rtc_web', + environment: import.meta.env.MODE, + level: 'ERROR', + error: { + type: error.name, + message: error.message, + file_path: match?.[1] || 'unknown', + line_number: parseInt(match?.[2] || '0'), + stack_trace: stackLines, + }, + context: { + url: window.location.href, + userAgent: navigator.userAgent, + ...context, + }, + }; + + // 使用 sendBeacon 确保页面关闭时也能发送 + if (navigator.sendBeacon) { + navigator.sendBeacon( + `${LOG_CENTER_URL}/api/v1/logs/report`, + JSON.stringify(payload) + ); + } else { + fetch(`${LOG_CENTER_URL}/api/v1/logs/report`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + keepalive: true, + }).catch(() => { }); // 静默失败 + } + } catch { + // 上报失败不影响主业务 + } +} + // 创建 Axios 实例 const request: AxiosInstance = axios.create({ baseURL: BASE_URL, @@ -48,6 +100,15 @@ request.interceptors.response.use( return data; }, (error: AxiosError<{ code: number; message: string }>) => { + // 上报到 Log Center + const apiError = new Error(error.message); + reportToLogCenter(apiError, { + url: error.config?.url, + method: error.config?.method, + status: error.response?.status, + responseData: error.response?.data, + }); + if (error.response) { const { status, data } = error.response; if (status === 401) { @@ -77,3 +138,6 @@ export interface PaginatedResponse { page: number; page_size: number; } + +// 导出 reportToLogCenter 供其他地方使用 +export { reportToLogCenter };