From 6ca787abf1b096e2f5dc97e600263d7a152e4da3 Mon Sep 17 00:00:00 2001 From: Orgad Shaneh Date: Wed, 20 Dec 2023 14:42:13 +0200 Subject: [PATCH] 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 #119. --- src/index.ts | 16 +++++++++------- test/index.ts | 6 +++--- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/index.ts b/src/index.ts index cba1f3b..8983ab8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -45,7 +45,12 @@ export interface RetryConfig { /** * Function to invoke when a retry attempt is made. */ - onRetryAttempt?: (error: AxiosError) => void; + onError?: (error: AxiosError) => void | Promise; + + /** + * Function to invoke when a retry attempt is made. + */ + onRetryAttempt?: (error: AxiosError) => void | Promise; /** * Function to invoke which determines if you should retry @@ -285,17 +290,14 @@ async function onError(instance: AxiosInstance, error: AxiosError) { setTimeout(resolve, delay); }); - // Notify the user if they added an `onRetryAttempt` handler - if (config.onRetryAttempt) { - config.onRetryAttempt(axiosError); + if (config.onError) { + await config.onError(axiosError); } - const onRetryAttemptPromise = Promise.resolve(); - // Return the promise in which recalls axios to retry the request return Promise.resolve() .then(async () => onBackoffPromise) - .then(async () => onRetryAttemptPromise) + .then(() => config.onRetryAttempt?.(axiosError)) .then(async () => config.instance!.request(axiosError.config!)); } diff --git a/test/index.ts b/test/index.ts index 8467fe5..63304b0 100644 --- a/test/index.ts +++ b/test/index.ts @@ -630,7 +630,7 @@ describe('retry-axios', () => { const axiosPromise = axios({ url, raxConfig: { - onRetryAttempt: resolve, + onError: resolve, retryDelay: 10_000, // Higher default to ensure Retry-After is used backoffType: 'static', }, @@ -660,7 +660,7 @@ describe('retry-axios', () => { const axiosPromise = axios({ url, raxConfig: { - onRetryAttempt: resolve, + onError: resolve, backoffType: 'static', retryDelay: 10_000, }, @@ -710,7 +710,7 @@ describe('retry-axios', () => { const axiosPromise = axios({ url, raxConfig: { - onRetryAttempt: resolve, + onError: resolve, retryDelay: 10_000, // Higher default to ensure maxRetryDelay is used maxRetryDelay: 5000, backoffType: 'exponential',