withRetry
withRetry<
T
>(operation
,opt?
,onError?
,retryErrorCodes?
):Promise
<T
>
Executes a synchronous or asynchronous operation with retries and exponential backoff.
Type Parameters
Section titled “Type Parameters”T
The type of the result returned by the operation.
Parameters
Section titled “Parameters”operation
Section titled “operation”(signal?
) => T
| Promise
<T
>
The synchronous or asynchronous operation to execute. Receives an optional
AbortSignal
that can be used to handle timeouts.
Optional configuration for retry behavior.
onError?
Section titled “onError?”(attempt
, err
) => void
| RetryAction
| Promise
<void | RetryAction>
Optional callback invoked after each failed attempt.
Receives the attempt number (starting at 1
) and the error thrown.
The callback can return a RetryAction to control whether
retries should continue (RetryAction.CONTINUE
) or stop (RetryAction.STOP
).
It may also return void
to continue retrying.
retryErrorCodes?
Section titled “retryErrorCodes?”string
[]
if provided, any error whose err.code
is not
in this array will not be retried
Returns
Section titled “Returns”Promise
<T
>
A promise that resolves with the result of the operation if successful.
If all retry attempts fail, the promise is rejected with an Error
whose cause
is set to the last error encountered.
Throws
Section titled “Throws”If the operation fails after all retries or
if an AbortError
is thrown during a timeout.
Example
Section titled “Example”// Attempt to fetch data up to 5 times with exponential backoff,// 1s base delay, 10s timeout per attempt, and custom stop logic.async function fetchDataWithRetry() { return await withRetry( async (signal) => { const res = await fetch('https://api.example.com/data', { signal }); if (!res.ok) { const err = new Error(`HTTP ${res.status}`); // attach code for retry filtering (err as any).code = String(res.status); throw err; } return await res.json(); }, { maxRetry: 5, baseDelay: 1000, timeout: 10_000, maxDelay: 20_000, }, (attempt, err) => { console.warn(`Attempt #${attempt} failed:`, err); // stop retrying on 404 Not Found if ((err as any).code === '404') { return RetryAction.STOP; } }, // Only retry on server errors (5xx) or timeouts ['500', '502', '503', '504'] );}
fetchDataWithRetry() .then(data => console.log('Data:', data)) .catch(err => console.error('Final failure:', err));