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 Dec 20, 2023
1 parent e888e95 commit cbb5f41
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
21 changes: 15 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>;

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

/**
* Function to invoke which determines if you should retry
Expand Down Expand Up @@ -285,17 +290,21 @@ 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();
// Notify the user if they added an `onRetryAttempt` handler
const onRetryAttemptPromise = async () => {
if (config.onRetryAttempt) {
await config.onRetryAttempt(axiosError);
}
};

// Return the promise in which recalls axios to retry the request
return Promise.resolve()
.then(async () => onBackoffPromise)
.then(async () => onRetryAttemptPromise)
.then(onRetryAttemptPromise)
.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 cbb5f41

Please sign in to comment.