fix: 代理失败日志增强 + undici ProxyAgent参数修正
This commit is contained in:
@@ -15,19 +15,21 @@ 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 { /* 未安装 */ }
|
||||||
|
|
||||||
|
// 尝试 undici(Node.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 调用) */
|
||||||
@@ -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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user