fix(login): 网络差浏览器未收到响应时友好提示
This commit is contained in:
1 parent
ce4b69eb7c
commit
64afe94924
6 files changed
+106
-2
No files matched your search
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* shared/api/client.networkError.spec.ts
|
||||
* 用途:锁定 fetch 网络失败不会把浏览器原文 Failed to fetch 交给界面。
|
||||
* 依赖:vitest、vue-i18n、requestJson。
|
||||
* 逻辑:模拟登录请求在拿到响应前失败,断言抛出 SYSTEM.NETWORK_ERROR 与本地化文案。
|
||||
*/
|
||||
import { describe, expect, it, vi, afterEach } from 'vitest';
|
||||
|
||||
vi.mock('@/i18n', async () => {
|
||||
const { createI18n } = await import('vue-i18n');
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
errors: {
|
||||
generic: '通用错误',
|
||||
codes: {
|
||||
SYSTEM_NETWORK_ERROR: '网络连接失败,请检查网络后重试。',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return { default: i18n };
|
||||
});
|
||||
|
||||
describe('requestJson network errors', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('maps Failed to fetch to a localized network message', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch')));
|
||||
const { requestJson, BusinessError } = await import('./client');
|
||||
|
||||
// 断言:登录等调用方拿到的是业务错误,正文不再是浏览器原文。
|
||||
await expect(requestJson('/api/user/casdoor/password-login', { method: 'POST', body: '{}' }))
|
||||
.rejects.toBeInstanceOf(BusinessError);
|
||||
await expect(requestJson('/api/user/casdoor/password-login', { method: 'POST', body: '{}' }))
|
||||
.rejects.toMatchObject({
|
||||
code: 'SYSTEM.NETWORK_ERROR',
|
||||
message: '网络连接失败,请检查网络后重试。',
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps caller aborts as AbortError', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new DOMException('The operation was aborted.', 'AbortError')));
|
||||
const { requestJson } = await import('./client');
|
||||
|
||||
// 断言:主动取消不能被误报成网络故障。
|
||||
await expect(requestJson('/api/user/login')).rejects.toMatchObject({ name: 'AbortError' });
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@
|
||||
* 跨域 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';
|
||||
@@ -118,6 +119,51 @@ function pickLegacyErrorMessage(payload: any): string | undefined {
|
||||
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<Response> {
|
||||
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<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
const headers = new Headers(init?.headers || {});
|
||||
const authHeaders = getAuthHeaders();
|
||||
@@ -127,7 +173,7 @@ export async function requestJson<T>(url: string, init?: RequestInit): Promise<T
|
||||
if (init?.body && !headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
const res = await fetch(url, { ...init, headers });
|
||||
const res = await fetchJsonResponse(url, { ...init, headers });
|
||||
|
||||
let data: any = null;
|
||||
try {
|
||||
@@ -192,7 +238,7 @@ export async function requestBlob(url: string, init?: RequestInit): Promise<Blob
|
||||
const headers = new Headers(init?.headers || {});
|
||||
const authHeaders = getAuthHeaders();
|
||||
Object.entries(authHeaders).forEach(([k, v]) => headers.set(k, v as string));
|
||||
const res = await fetch(url, { ...init, headers });
|
||||
const res = await fetchJsonResponse(url, { ...init, headers });
|
||||
const requestIdHeader = res.headers.get('X-Request-Id') || undefined;
|
||||
const contentType = (res.headers.get('Content-Type') || '').toLowerCase();
|
||||
|
||||
|
||||
Reference in new issue
Block a user