Skip to content

Commit

Permalink
fix: Call onRetryAttempt *after* backoff timeout
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
orgads committed Jun 13, 2024
1 parent 1401ac7 commit 04e032e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
16 changes: 9 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,15 @@ export interface RetryConfig {
*/
statusCodesToRetry?: number[][];

/**
* Function to invoke when error occurred.
*/
onError?: (error: AxiosError) => void | Promise<void>;

/**
* Function to invoke when a retry attempt is made.
*/
onRetryAttempt?: (error: AxiosError) => void;
onRetryAttempt?: (error: AxiosError) => void | Promise<void>;

/**
* Function to invoke which determines if you should retry
Expand Down Expand Up @@ -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(async () => config.onRetryAttempt?.(axiosError))
.then(async () => config.instance!.request(axiosError.config!));
}

Expand Down
6 changes: 3 additions & 3 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
},
Expand Down Expand Up @@ -660,7 +660,7 @@ describe('retry-axios', () => {
const axiosPromise = axios({
url,
raxConfig: {
onRetryAttempt: resolve,
onError: resolve,
backoffType: 'static',
retryDelay: 10_000,
},
Expand Down Expand Up @@ -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',
Expand Down

0 comments on commit 04e032e

Please sign in to comment.