/** * shared/api/client.ts * 跨域 HTTP 客户端:envelope 解析、BusinessError、requestJson、requestBlob。 * 依赖:auth、vue-i18n、shared/utils/download(Content-Disposition 文件名)。 * 所有 feature API 层应通过此模块发起请求;二进制下载走 requestBlob,失败仍为 BusinessError。 * fetch 在收到 HTTP 响应前失败时转为 SYSTEM.NETWORK_ERROR,避免把浏览器原文 Failed to fetch 展示给用户。 */ import { getAuthHeaders } from '@/shared/utils/auth'; import { parseContentDispositionFilename } from '@/shared/utils/download'; import i18n from '@/i18n'; export interface ApiSuccessEnvelope { success: true; data: T; request_id?: string; timestamp?: string; } export interface ApiErrorBody { code?: string; message?: string; details?: Record; retryable?: boolean; } export interface ApiErrorEnvelope { success: false; error?: ApiErrorBody; request_id?: string; timestamp?: string; } export class BusinessError extends Error { code: string; details: Record; requestId?: string; status?: number; constructor(args: { message: string; code?: string; details?: Record; requestId?: string; status?: number }) { super(args.message); this.name = 'BusinessError'; this.code = args.code || 'SYSTEM.UNKNOWN'; this.details = args.details || {}; this.requestId = args.requestId; this.status = args.status; } } /** * 按错误码解析当前语言文案,供 requestJson 与认证二进制下载共用。 * @param code - 后端 AppError 机器码 * @param fallbackMessage - 未配置错误码时的后端说明 * @returns 当前语言的用户可见错误信息 */ export function resolveLocalizedErrorMessage(code?: string, fallbackMessage?: string): string { const fallback = String(fallbackMessage || '').trim(); const isGenericFallback = (msg: string) => { const v = msg.trim().toLowerCase(); if (!v) return true; if (v === 'invalid request parameters' || v === 'invalid request parameters.') return true; if (v === 'request failed' || v === 'request failed.') return true; if (v.startsWith('http ')) return true; return false; }; /** * 在 errors.codes 中查找文案:优先字面量键(含点号),再尝试下划线键与路径解析。 */ const lookupCodeMessage = (rawCode: string): string | null => { const bag = i18n.global.tm('errors.codes') as Record | string | null; if (bag && typeof bag === 'object' && !Array.isArray(bag)) { const direct = bag[rawCode]; if (typeof direct === 'string' && direct.trim()) return direct; const underscoredLeaf = rawCode.replace(/\./g, '_'); const viaUnderscore = bag[underscoredLeaf]; if (typeof viaUnderscore === 'string' && viaUnderscore.trim()) return viaUnderscore; } const underscoredPath = `errors.codes.${rawCode.replace(/\./g, '_')}`; if (i18n.global.te(underscoredPath)) return String(i18n.global.t(underscoredPath)); const dottedPath = `errors.codes.${rawCode}`; if (i18n.global.te(dottedPath)) return String(i18n.global.t(dottedPath)); return null; }; if (code) { const localized = lookupCodeMessage(code); if (localized) { const normalizedCode = code.replace(/\./g, '_'); if (normalizedCode === 'VALIDATION_INVALID_PARAM' && fallback && !isGenericFallback(fallback) && fallback !== localized) { return `${localized} ${fallback}`; } if ( normalizedCode === 'AUTH_FORBIDDEN' && fallback && !isGenericFallback(fallback) && fallback.toLowerCase() !== 'forbidden' && fallback !== localized ) { return fallback; } return localized; } } if (fallback) return fallback; if (i18n.global.te('errors.generic')) { return String(i18n.global.t('errors.generic')); } return code || 'Request failed'; } export const isEnvelope = (payload: any): payload is ApiSuccessEnvelope | ApiErrorEnvelope => { return !!payload && typeof payload === 'object' && typeof payload.success === 'boolean'; }; function pickLegacyErrorMessage(payload: any): string | undefined { if (!payload) return undefined; if (typeof payload.error === 'string' && payload.error.trim()) return payload.error; if (typeof payload.message === 'string' && payload.message.trim()) return payload.message; return undefined; } /** Chrome / Firefox / Safari 在 fetch 未拿到响应时的原文,大小写不敏感匹配。 */ const FETCH_NETWORK_ERROR_PATTERNS = [ 'failed to fetch', 'load failed', 'networkerror when attempting to fetch resource', 'network error', ]; /** * 判断 fetch 是否在拿到 HTTP 响应前就失败。 * 核心逻辑:只认浏览器原生断网/超时/DNS 类错误;AbortError 是调用方主动取消,不当成网络故障。 * @param error - fetch 抛出的异常 * @returns 是否应转成 SYSTEM.NETWORK_ERROR */ function isFetchNetworkError(error: unknown): boolean { if (!(error instanceof Error)) return false; if (error.name === 'AbortError') return false; if (error.name === 'NetworkError') return true; const message = error.message.trim().toLowerCase(); if (!message) return false; return FETCH_NETWORK_ERROR_PATTERNS.some( (pattern) => message === pattern || message.includes(pattern), ); } /** * 发起 fetch;网络层失败时抛出已本地化的 BusinessError,而不是浏览器原文。 * 核心逻辑:捕获 TypeError(Failed to fetch / Load failed 等)后映射为 SYSTEM.NETWORK_ERROR。 * @param url - 请求地址 * @param init - fetch 初始化参数 * @returns HTTP 响应 * @throws BusinessError 网络不可达时,code 为 SYSTEM.NETWORK_ERROR */ async function fetchJsonResponse(url: string, init: RequestInit): Promise { try { return await fetch(url, init); } catch (error) { if (!isFetchNetworkError(error)) throw error; throw new BusinessError({ message: resolveLocalizedErrorMessage('SYSTEM.NETWORK_ERROR'), code: 'SYSTEM.NETWORK_ERROR', }); } } export async function requestJson(url: string, init?: RequestInit): Promise { const headers = new Headers(init?.headers || {}); const authHeaders = getAuthHeaders(); Object.entries(authHeaders).forEach(([k, v]) => headers.set(k, v as string)); const res = await fetchJsonResponse(url, { ...init, headers }); let data: any = null; try { data = await res.json(); } catch { if (!res.ok) { throw new BusinessError({ message: `HTTP ${res.status}`, code: 'SYSTEM.HTTP_ERROR', status: res.status, }); } return null as T; } if (!res.ok) { if (isEnvelope(data) && data.success === false) { throw new BusinessError({ message: resolveLocalizedErrorMessage(data.error?.code, data.error?.message || `HTTP ${res.status}`), code: data.error?.code, details: data.error?.details, requestId: data.request_id, status: res.status, }); } throw new BusinessError({ message: resolveLocalizedErrorMessage(data?.code, pickLegacyErrorMessage(data) || `HTTP ${res.status}`), code: data?.code || data?.error_code || 'SYSTEM.HTTP_ERROR', details: data?.details || {}, requestId: data?.request_id, status: res.status, }); } if (isEnvelope(data)) { if (data.success === true) return data.data as T; throw new BusinessError({ message: resolveLocalizedErrorMessage(data.error?.code, data.error?.message || 'Request failed'), code: data.error?.code, details: data.error?.details, requestId: data.request_id, status: res.status, }); } return data as T; } export type BlobDownloadResult = { blob: Blob; filename?: string; requestId?: string; }; /** * 发起需鉴权的二进制下载;失败时按 Envelope 解析为 BusinessError(与 requestJson 同源)。 * @param url - 请求路径 * @param init - fetch 初始化参数 * @returns blob 与可选文件名、request_id */ export async function requestBlob(url: string, init?: RequestInit): Promise { const headers = new Headers(init?.headers || {}); const authHeaders = getAuthHeaders(); Object.entries(authHeaders).forEach(([k, v]) => headers.set(k, v as string)); const res = await fetchJsonResponse(url, { ...init, headers }); const requestIdHeader = res.headers.get('X-Request-Id') || undefined; const contentType = (res.headers.get('Content-Type') || '').toLowerCase(); if (!res.ok) { let data: any = null; if (contentType.includes('application/json')) { try { data = await res.json(); } catch { data = null; } } if (data && isEnvelope(data) && data.success === false) { throw new BusinessError({ message: resolveLocalizedErrorMessage(data.error?.code, data.error?.message || `HTTP ${res.status}`), code: data.error?.code, details: data.error?.details, requestId: data.request_id || requestIdHeader, status: res.status, }); } throw new BusinessError({ message: resolveLocalizedErrorMessage(data?.code, pickLegacyErrorMessage(data) || `HTTP ${res.status}`), code: data?.code || data?.error_code || 'SYSTEM.HTTP_ERROR', details: data?.details || {}, requestId: data?.request_id || requestIdHeader, status: res.status, }); } const blob = await res.blob(); return { blob, filename: parseContentDispositionFilename(res.headers.get('Content-Disposition')), requestId: requestIdHeader, }; }