UNPKG

sync-upstream

Version:

A tool for synchronizing code with upstream repositories with incremental updates and parallel processing.

45 lines (44 loc) 1.87 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.withRetry = withRetry; const errors_1 = require("./errors"); const logger_1 = require("./logger"); /** * 通用重试工具函数 * @param fn 要执行的异步函数 * @param config 重试配置 * @param isNetworkError 判断是否为网络错误的函数 * @returns 函数执行结果 */ async function withRetry(fn, config, isNetworkError = (error) => { const message = error.message.toLowerCase(); return message.includes('network') || message.includes('connect'); }) { let lastError; for (let attempt = 0; attempt <= config.maxRetries; attempt++) { try { if (attempt > 0) { const delay = config.initialDelay * config.backoffFactor ** (attempt - 1); logger_1.logger.info(`正在进行第 ${attempt}/${config.maxRetries} 次重试,延迟 ${delay}ms...`); await new Promise(resolve => setTimeout(resolve, delay)); } return await fn(); } catch (error) { lastError = error; // 只有网络错误才重试 if (!isNetworkError(lastError)) { logger_1.logger.error(`非网络错误,不进行重试: ${lastError.message}`); throw lastError; } // 如果达到最大重试次数,则抛出错误 if (attempt >= config.maxRetries) { logger_1.logger.error(`达到最大重试次数(${config.maxRetries}),请求失败: ${lastError.message}`); throw new errors_1.NetworkError('网络请求失败', lastError); } logger_1.logger.warn(`请求失败(第 ${attempt} 次尝试): ${lastError.message}`); } } // 理论上不会到达这里,但为了类型安全 throw lastError; }