LaiTool 3.0.1
This commit is contained in:
@@ -9,3 +9,31 @@ export function ContainsChineseOrPunctuation(str: string): boolean {
|
||||
str
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用的重试函数
|
||||
* @param fn 要执行的函数
|
||||
* @param retries 最大重试次数
|
||||
* @param delay 每次重试之间的延迟(毫秒)
|
||||
* @returns 返回函数的结果
|
||||
*/
|
||||
export async function RetryWithBackoff<T>(fn: () => Promise<T>, retries: number = 5, delay: number = 2000): Promise<T> {
|
||||
let attempts = 0;
|
||||
while (attempts < retries) {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (error) {
|
||||
attempts++;
|
||||
// 这边记下日志吧
|
||||
global.logger.error(
|
||||
fn.name + '_RetryWithBackoff',
|
||||
`第 ${attempts} 请求失败,开始下一次重试,失败信息如下:` + error.toString()
|
||||
)
|
||||
if (attempts >= retries) {
|
||||
throw new Error(`失败次数超过 ${retries} 错误信息如下: ${error.message}`);
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, delay));
|
||||
}
|
||||
}
|
||||
throw new Error('所有重试失败'); // 理论上不会到达这里
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user