http.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import type { SmsConfig } from '../types/smsTypes.ts'
  2. export async function fetchWithRetry(
  3. url: string,
  4. options: {
  5. method: string
  6. headers: Record<string, string>
  7. body: string
  8. timeout: number
  9. maxRetries: number
  10. }
  11. ): Promise<Response> {
  12. let lastError: unknown = null
  13. for (let attempt = 0; attempt <= options.maxRetries; attempt++) {
  14. try {
  15. const controller = new AbortController()
  16. const timeoutId = setTimeout(
  17. () => controller.abort(),
  18. options.timeout
  19. )
  20. const response = await fetch(url, {
  21. ...options,
  22. signal: controller.signal
  23. })
  24. clearTimeout(timeoutId)
  25. return response
  26. } catch (error) {
  27. lastError = error instanceof Error ? error : new Error(String(error))
  28. if (attempt < options.maxRetries) {
  29. await new Promise(resolve =>
  30. setTimeout(resolve, 1000 * (attempt + 1)))
  31. }
  32. }
  33. }
  34. throw lastError instanceof Error ? lastError : new Error(String(lastError || '请求失败'))
  35. }