fix: 修复请求解析失败、端口重试和重复报错

This commit is contained in:
2026-10-25 07:37:08 +08:00
parent 545945b543
commit 07180b162b
2 changed files with 74 additions and 18 deletions
+52 -13
View File
@@ -1,15 +1,51 @@
let apiBase = "";
let preparing: Promise<void> | null = null;
let deepScanDone = false;
type UnauthorizedHandler = () => void;
let unauthorizedHandler: UnauthorizedHandler | null = null;
let unauthorizedNotified = false;
export function setUnauthorizedHandler(handler: UnauthorizedHandler | null) {
unauthorizedHandler = handler;
}
export function clearUnauthorized() {
unauthorizedNotified = false;
}
function notifyUnauthorized() {
if (unauthorizedNotified) return;
unauthorizedNotified = true;
unauthorizedHandler?.();
}
export class ApiError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.name = "ApiError";
this.status = status;
}
}
export function initApi(): Promise<void> {
preparing ??= resolveApiBase();
if (!preparing) {
preparing = resolveApiBase().catch((error: unknown) => {
preparing = null;
throw error;
});
}
return preparing;
}
async function resolveApiBase(): Promise<void> {
if (!("__TAURI_INTERNALS__" in window)) return;
const { invoke } = await import("@tauri-apps/api/core");
for (let attempt = 0; attempt < 50; attempt += 1) {
const attempts = deepScanDone ? 1 : 50;
deepScanDone = true;
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
const port = await invoke<number>("backend_port");
if (port > 0) {
@@ -19,17 +55,11 @@ async function resolveApiBase(): Promise<void> {
} catch {
// 窗口可能比端口命令更早就绪。
}
await new Promise((resolve) => window.setTimeout(resolve, 100));
}
}
export class ApiError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
if (attempt + 1 < attempts) {
await new Promise((resolve) => window.setTimeout(resolve, 100));
}
}
throw new ApiError(0, "连接失败");
}
export async function api<T>(path: string, init?: RequestInit): Promise<T> {
@@ -45,7 +75,16 @@ export async function api<T>(path: string, init?: RequestInit): Promise<T> {
throw new ApiError(0, "连接失败");
}
const text = await response.text();
const data = text ? JSON.parse(text) : null;
let data: { detail?: unknown } | null = null;
if (text) {
try {
data = JSON.parse(text) as { detail?: unknown };
} catch {
if (response.status === 401) notifyUnauthorized();
throw new ApiError(response.status, `服务出错(${response.status})`);
}
}
if (response.status === 401) notifyUnauthorized();
if (!response.ok) {
const detail = data?.detail;
const message = typeof detail === "string" ? detail : "请求失败";