import { notifyError } from '@lingxi/ui'; import { MutationCache, type Query, QueryCache, QueryClient } from '@tanstack/react-query'; import { ApiError } from './client'; type CacheQuery = Query; function reportError(error: unknown, query?: CacheQuery): void { // 背景轮询(如顶栏任务角标)失败不弹全局 toast:页面自身有状态提示,断网时避免反复打扰 if (query !== undefined && query.meta?.suppressToast === true) { return; } if (error instanceof ApiError) { if (error.status === 401) { return; } notifyError(error.message, error.traceId); return; } notifyError(error instanceof Error ? error.message : '网络请求失败,请稍后重试'); } function shouldRetry(failureCount: number, error: unknown): boolean { if (failureCount >= 2) { return false; } if (error instanceof ApiError) { return error.status >= 500 || error.status === 429; } return true; } export const queryClient = new QueryClient({ queryCache: new QueryCache({ onError: (error, query) => { reportError(error, query); }, }), mutationCache: new MutationCache({ onError: (error) => { reportError(error); }, }), defaultOptions: { queries: { retry: shouldRetry, refetchOnWindowFocus: false, staleTime: 30_000, }, }, });