(
fn: () => Promise<T>,
options: RetryOptions = {}
)
| 55 | * Retry a function with exponential backoff |
| 56 | */ |
| 57 | export async function retryWithBackoff<T>( |
| 58 | fn: () => Promise<T>, |
| 59 | options: RetryOptions = {} |
| 60 | ): Promise<T> { |
| 61 | const opts = { ...DEFAULT_OPTIONS, ...options }; |
| 62 | let lastError: any; |
| 63 | |
| 64 | for (let attempt = 0; attempt <= opts.maxRetries; attempt++) { |
| 65 | try { |
| 66 | return await fn(); |
| 67 | } catch (error) { |
| 68 | lastError = error; |
| 69 | |
| 70 | // Don't retry if this is the last attempt |
| 71 | if (attempt === opts.maxRetries) { |
| 72 | break; |
| 73 | } |
| 74 | |
| 75 | // Don't retry if error is not retryable |
| 76 | if (!isRetryableError(error, opts.retryableErrors)) { |
| 77 | console.error(`Non-retryable error encountered:`, error); |
| 78 | throw error; |
| 79 | } |
| 80 | |
| 81 | const delay = calculateDelay(attempt, opts.baseDelay, opts.maxDelay); |
| 82 | console.log( |
| 83 | `Attempt ${attempt + 1} failed. Retrying in ${delay}ms... Error: ${error}` |
| 84 | ); |
| 85 | |
| 86 | await sleep(delay); |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | console.error(`All ${opts.maxRetries + 1} attempts failed. Last error:`, lastError); |
| 91 | throw lastError; |
| 92 | } |
no test coverage detected