diff --git a/frontend/src/core/models/api.ts b/frontend/src/core/models/api.ts index 362bb0d7..d0babc18 100644 --- a/frontend/src/core/models/api.ts +++ b/frontend/src/core/models/api.ts @@ -4,6 +4,15 @@ import type { Model } from "./types"; export async function loadModels() { const res = await fetch(`${getBackendBaseURL()}/api/models`); + + if (res.status >= 500 && res.status < 600) { + throw new Error(`Server error: ${res.status}`); + } + + if (!res.ok) { + throw new Error(`HTTP error: ${res.status}`); + } + const { models } = (await res.json()) as { models: Model[] }; return models; } diff --git a/frontend/src/core/models/hooks.ts b/frontend/src/core/models/hooks.ts index 2becbbbc..f0fa7536 100644 --- a/frontend/src/core/models/hooks.ts +++ b/frontend/src/core/models/hooks.ts @@ -1,13 +1,34 @@ import { useQuery } from "@tanstack/react-query"; +import { useEffect } from "react"; +import { toast } from "sonner"; import { loadModels } from "./api"; +import type { Model } from "./types"; export function useModels({ enabled = true }: { enabled?: boolean } = {}) { - const { data, isLoading, error } = useQuery({ + const { data, isLoading, error } = useQuery({ queryKey: ["models"], queryFn: () => loadModels(), enabled, refetchOnWindowFocus: false, + retry: (failureCount, queryError) => { + if (queryError.message.startsWith("HTTP error: 4")) { + return false; + } + return failureCount < 1; + }, }); + + useEffect(() => { + // React Query v5 removed per-query onError callbacks from useQuery options. + if (error?.message.includes("Server error: 5")) { + toast.error("系统正在更新-5,请稍候……"); + } + + if (error?.message.includes("HTTP error: 4")) { + toast.error("模型接口不可用,请检查后端路由或服务状态。"); + } + }, [error]); + return { models: data ?? [], isLoading, error }; }