fix: 代理失败日志增强 + undici ProxyAgent参数修正

This commit is contained in:
thzxx
2026-06-10 16:09:47 +08:00
parent 25809c1532
commit c718d99108
+19 -12
View File
@@ -15,20 +15,22 @@ let _proxyUrl = '';
function getProxyAgent(): any { function getProxyAgent(): any {
if (!_proxyUrl) return null; if (!_proxyUrl) return null;
// 尝试 https-proxy-agent(需 npm install
try { try {
const url = new URL(_proxyUrl);
const { HttpsProxyAgent } = require('https-proxy-agent'); const { HttpsProxyAgent } = require('https-proxy-agent');
return new HttpsProxyAgent(url); const a = new HttpsProxyAgent(_proxyUrl);
} catch { return a;
// https-proxy-agent 不可用,尝试 undici } catch { /* 未安装 */ }
// 尝试 undiciNode.js 内置)
try { try {
const { ProxyAgent } = require('undici'); const { ProxyAgent } = require('undici');
return new ProxyAgent(_proxyUrl); return new ProxyAgent({ uri: _proxyUrl });
} catch { } catch { /* 不可用 */ }
return null; return null;
} }
}
}
/** 设置 HTTP 代理(供 IPC 调用) */ /** 设置 HTTP 代理(供 IPC 调用) */
export function setProxyUrl(url: string): void { export function setProxyUrl(url: string): void {
@@ -212,16 +214,21 @@ async function fetchWithTimeout(url: string, timeout = HTTP_TIMEOUT, headers?: R
const timeoutId = setTimeout(() => controller.abort(), timeout); const timeoutId = setTimeout(() => controller.abort(), timeout);
try { try {
const agent = getProxyAgent(); const agent = getProxyAgent();
const resp = await fetch(url, { const fetchOpts: any = {
headers: _headers, headers: _headers,
signal: controller.signal, signal: controller.signal,
redirect: 'follow', redirect: 'follow',
...(agent && { dispatcher: agent }), };
}); if (agent) fetchOpts.dispatcher = agent;
const resp = await fetch(url, fetchOpts);
clearTimeout(timeoutId); clearTimeout(timeoutId);
return resp; return resp;
} catch { } catch (err) {
clearTimeout(timeoutId); clearTimeout(timeoutId);
if (_proxyUrl) {
const msg = (err as Error).message || '';
sendLog('warn', `🌐 fetch 失败`, `${url.slice(0, 80)} | 代理=${_proxyUrl} | ${msg.slice(0, 100)}`);
}
return null; return null;
} }
} }