From 4f15bdf74deef2f6d86da7ad474ae35725686572 Mon Sep 17 00:00:00 2001 From: wonfen Date: Sun, 20 Apr 2025 10:34:43 +0800 Subject: [PATCH] feat: add IP info request retry mechanism to reduce network errors --- UPDATELOG.md | 1 + src/services/api.ts | 51 ++++++++++++++++++++++++++++++++------------- 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/UPDATELOG.md b/UPDATELOG.md index 473576d5..f12a29e7 100644 --- a/UPDATELOG.md +++ b/UPDATELOG.md @@ -21,6 +21,7 @@ #### 优化了: - 系统代理 Bypass 设置 - Windows 下使用 Startup 文件夹的方式实现开机自启,解决管理员模式下开机自启的各种问题 + - 增加 IP 信息请求重试机制,减少 Network Error 发生的情况 ## v2.2.3 diff --git a/src/services/api.ts b/src/services/api.ts index d2abad0f..9feb34dd 100644 --- a/src/services/api.ts +++ b/src/services/api.ts @@ -321,19 +321,40 @@ export const gc = async () => { // Get current IP and geolocation information export const getIpInfo = async () => { - // 使用axios直接请求IP.sb的API,不通过clash代理 - const response = await axios.get("https://api.ip.sb/geoip"); - return response.data as { - ip: string; - country_code: string; - country: string; - region: string; - city: string; - organization: string; - asn: number; - asn_organization: string; - longitude: number; - latitude: number; - timezone: string; - }; + // 添加重试机制 + const maxRetries = 3; + const retryDelay = 1500; + const timeout = 5000; + + let lastError; + + for (let attempt = 0; attempt < maxRetries; attempt++) { + try { + // 使用axios直接请求IP.sb的API,不通过clash代理 + const response = await axios.get("https://api.ip.sb/geoip", { timeout }); + return response.data as { + ip: string; + country_code: string; + country: string; + region: string; + city: string; + organization: string; + asn: number; + asn_organization: string; + longitude: number; + latitude: number; + timezone: string; + }; + } catch (error) { + console.log(`获取IP信息失败,尝试 ${attempt + 1}/${maxRetries}`, error); + lastError = error; + + // 如果不是最后一次尝试,则等待后重试 + if (attempt < maxRetries - 1) { + await new Promise(resolve => setTimeout(resolve, retryDelay)); + } + } + } + + throw lastError; };