Skip to content

Commit 12ce1c8

Browse files
committed
fix: Call onRetryAttempt *after* backoff timeout
The log appears before the timeout, which is misleading. Also return support for async onRetryAttempt. Introduce a new onError callback that is called before the timeout. Fixes JustinBeckwith#119.
1 parent e888e95 commit 12ce1c8

File tree

2 files changed

+18
-9
lines changed

2 files changed

+18
-9
lines changed

src/index.ts

+15-6
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,12 @@ export interface RetryConfig {
4545
/**
4646
* Function to invoke when a retry attempt is made.
4747
*/
48-
onRetryAttempt?: (error: AxiosError) => void;
48+
onError?: (error: AxiosError) => void | Promise<void>;
49+
50+
/**
51+
* Function to invoke when a retry attempt is made.
52+
*/
53+
onRetryAttempt?: (error: AxiosError) => void | Promise<void>;
4954

5055
/**
5156
* Function to invoke which determines if you should retry
@@ -285,17 +290,21 @@ async function onError(instance: AxiosInstance, error: AxiosError) {
285290
setTimeout(resolve, delay);
286291
});
287292

288-
// Notify the user if they added an `onRetryAttempt` handler
289-
if (config.onRetryAttempt) {
290-
config.onRetryAttempt(axiosError);
293+
if (config.onError) {
294+
await config.onError(axiosError);
291295
}
292296

293-
const onRetryAttemptPromise = Promise.resolve();
297+
// Notify the user if they added an `onRetryAttempt` handler
298+
const onRetryAttemptPromise = async () => {
299+
if (config.onRetryAttempt) {
300+
await config.onRetryAttempt(axiosError);
301+
}
302+
}
294303

295304
// Return the promise in which recalls axios to retry the request
296305
return Promise.resolve()
297306
.then(async () => onBackoffPromise)
298-
.then(async () => onRetryAttemptPromise)
307+
.then(onRetryAttemptPromise)
299308
.then(async () => config.instance!.request(axiosError.config!));
300309
}
301310

test/index.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -630,7 +630,7 @@ describe('retry-axios', () => {
630630
const axiosPromise = axios({
631631
url,
632632
raxConfig: {
633-
onRetryAttempt: resolve,
633+
onError: resolve,
634634
retryDelay: 10_000, // Higher default to ensure Retry-After is used
635635
backoffType: 'static',
636636
},
@@ -660,7 +660,7 @@ describe('retry-axios', () => {
660660
const axiosPromise = axios({
661661
url,
662662
raxConfig: {
663-
onRetryAttempt: resolve,
663+
onError: resolve,
664664
backoffType: 'static',
665665
retryDelay: 10_000,
666666
},
@@ -710,7 +710,7 @@ describe('retry-axios', () => {
710710
const axiosPromise = axios({
711711
url,
712712
raxConfig: {
713-
onRetryAttempt: resolve,
713+
onError: resolve,
714714
retryDelay: 10_000, // Higher default to ensure maxRetryDelay is used
715715
maxRetryDelay: 5000,
716716
backoffType: 'exponential',

0 commit comments

Comments
 (0)