Throw Exponential Backoff error containing all execution errors
This commit is contained in:
@@ -2,8 +2,8 @@
|
||||
* Error thrown when the maximum number of retries is hit in an exponential backoff
|
||||
*/
|
||||
export class ExponentialBackoffMaxRetriesHitError extends Error {
|
||||
constructor() {
|
||||
super('Exponential backoff: Max retries hit');
|
||||
constructor(errors: Array<Error>) {
|
||||
super('Exponential backoff: Max retries hit', { cause: errors });
|
||||
this.name = 'ExponentialBackoffMaxRetriesHitError';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,17 +70,18 @@ export class ExponentialBackoff {
|
||||
* If the function fails but we have not hit the max attempts, the error will be passed to the onError callback
|
||||
* and the function will be retried with an exponential delay
|
||||
*
|
||||
* If the function fails and we have hit the max attempts, the last error will be thrown
|
||||
* If the function fails and we have hit the max attempts, an ExponentialBackoffMaxRetriesHitError will be thrown with all the errors that were thrown by the task function
|
||||
*
|
||||
* @param fn - The function to run
|
||||
* @param onError - The callback to call when an error occurs
|
||||
*
|
||||
* @throws The last error if the function fails and we have hit the max attempts
|
||||
* @throws An ExponentialBackoffMaxRetriesHitError with all the errors that were thrown by the task function
|
||||
*
|
||||
* @returns The result of the function
|
||||
*/
|
||||
async run<T>(taskFn: () => Promise<T>, onError = (_error: Error): void => {}): Promise<T> {
|
||||
let lastError: Error = new ExponentialBackoffMaxRetriesHitError();
|
||||
// Initialize an empty array to store the errors
|
||||
const errors: Error[] = [];
|
||||
|
||||
let attempt = 0;
|
||||
|
||||
@@ -92,8 +93,9 @@ export class ExponentialBackoff {
|
||||
return await taskFn();
|
||||
} catch (error) {
|
||||
// Store the error in case we fail every attempt
|
||||
lastError = error instanceof Error ? error : new Error(`${error}`);
|
||||
onError(lastError);
|
||||
const errorInstance = error instanceof Error ? error : new Error(`${error}`);
|
||||
errors.push(errorInstance);
|
||||
onError(errorInstance);
|
||||
|
||||
// Wait before going to the next attempt
|
||||
const delay = ExponentialBackoff.calculateDelay(this.options, attempt);
|
||||
@@ -103,8 +105,8 @@ export class ExponentialBackoff {
|
||||
attempt++;
|
||||
}
|
||||
|
||||
// We completed the loop without ever succeeding. Throw the last error we got
|
||||
throw lastError;
|
||||
// We completed the loop without ever succeeding. Throw an ExponentialBackoffMaxRetriesHitError with all the errors we got
|
||||
throw new ExponentialBackoffMaxRetriesHitError(errors);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user