| 1234567891011121314151617181920212223242526272829303132333435363738394041 |
- import type { SmsConfig } from '../types/smsTypes.ts'
- export async function fetchWithRetry(
- url: string,
- options: {
- method: string
- headers: Record<string, string>
- body: string
- timeout: number
- maxRetries: number
- }
- ): Promise<Response> {
- let lastError: unknown = null
-
- for (let attempt = 0; attempt <= options.maxRetries; attempt++) {
- try {
- const controller = new AbortController()
- const timeoutId = setTimeout(
- () => controller.abort(),
- options.timeout
- )
- const response = await fetch(url, {
- ...options,
- signal: controller.signal
- })
- clearTimeout(timeoutId)
- return response
- } catch (error) {
- lastError = error instanceof Error ? error : new Error(String(error))
- if (attempt < options.maxRetries) {
- await new Promise(resolve =>
- setTimeout(resolve, 1000 * (attempt + 1)))
- }
- }
- }
- throw lastError instanceof Error ? lastError : new Error(String(lastError || '请求失败'))
- }
|