Skip to content

Commit eef8d48

Browse files
authored
Merge pull request #44 from ubio/feat-allow-custom-evaluate-to-retry-on-error-from-request
Feat: allow custom evaluate to retry on error from request
2 parents 26ff94f + ca19e85 commit eef8d48

3 files changed

Lines changed: 34 additions & 1 deletion

File tree

src/main/request.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ export const DEFAULT_REQUEST_CONFIG: RequestConfig = {
2727
retryDelayIncrement: 500,
2828
retryStatusCodes: [429, 502, 503, 504],
2929
authInvalidateStatusCodes: [401, 403],
30+
handleShouldRetry: () => false,
3031
headers: {},
3132
fetch,
3233
};
@@ -108,7 +109,7 @@ export class Request {
108109
const status = err.details?.status;
109110
const statusText = err.details?.statusText;
110111
const info: RequestDebugInfo = { method, url, headers: options.headers ?? {}, status, statusText };
111-
const retry = shouldRetry || NETWORK_ERRORS.includes(err.code);
112+
const retry = shouldRetry || NETWORK_ERRORS.includes(err.code) || this.config.handleShouldRetry?.(err);
112113
if (retry) {
113114
lastError = err;
114115
lastInfo = info;

src/main/types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ export interface RequestConfig {
2828
authInvalidateStatusCodes: number[];
2929
headers: RequestHeaders;
3030
fetch: Fetch;
31+
handleShouldRetry?: (error: Error) => boolean;
3132
}
3233

3334
export interface Fetch {

src/test/request.test.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,37 @@ describe('Request', () => {
8484
assert.strictEqual(thrownError.details.status, 504);
8585
});
8686

87+
it('retry if handleShouldRetry returns true', async () => {
88+
let thrownError: any;
89+
const fetch = fetchMock({ status: 500 });
90+
const request = new Request({
91+
fetch,
92+
retryAttempts,
93+
retryDelay: 0,
94+
retryDelayIncrement: 10,
95+
handleShouldRetry: err => {
96+
err.message = 'should-retry';
97+
return true;
98+
},
99+
});
100+
request.onRetry = err => { thrownError = err; };
101+
await request.send('get', 'http://example.com').catch(() => {});
102+
assert.ok(thrownError);
103+
assert.strictEqual(thrownError.message, 'should-retry');
104+
assert.strictEqual(thrownError.details.status, 500);
105+
});
106+
107+
it('do not retry by default config', async () => {
108+
let retried = false;
109+
const fetch = fetchMock({ status: 500 });
110+
const request = new Request({
111+
fetch
112+
});
113+
request.onRetry = () => { retried = true; };
114+
await request.send('get', 'http://example.com').catch(() => {});
115+
assert.ok(!retried);
116+
});
117+
87118
});
88119

89120
describe('mergeHeaders', () => {

0 commit comments

Comments
 (0)