Last active
December 23, 2024 10:43
-
-
Save crypt0miester/8bf545536011a89daf16d73720aa1de3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type RetryConfig = { | |
maxAttempts?: number; | |
initialDelay?: number; | |
maxDelay?: number; | |
backoffFactor?: number; | |
onRetry?: (error: Error, attempt: number) => void; | |
}; | |
export async function retryOnFailure<T>( | |
operation: () => Promise<T>, | |
config: RetryConfig = {}, | |
): Promise<T> { | |
const { | |
maxAttempts = 3, | |
initialDelay = 1000, | |
maxDelay = 5000, | |
backoffFactor = 2, | |
onRetry = () => {}, | |
} = config; | |
let lastError: Error; | |
let delay = initialDelay; | |
for (let attempt = 1; attempt <= maxAttempts; attempt++) { | |
try { | |
return await operation(); | |
} catch (error) { | |
lastError = error as Error; | |
if (attempt === maxAttempts) { | |
throw lastError; | |
} | |
// call the onRetry callback | |
onRetry(lastError, attempt); | |
// sleep before retrying | |
await new Promise((resolve) => setTimeout(resolve, delay)); | |
// calculate next delay with exponential backoff | |
delay = Math.min(delay * backoffFactor, maxDelay); | |
} | |
} | |
throw lastError!; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to use: