Preserve non-Error values in retry errors and hooks
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 06ebf18 · Browse files · 4 files·+76 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+76 added−4 removed
- tests:+72 added−0 removed
- other:+4 added−4 removed
Provenance
- Commit
87a96db- Tree
c78cbe4- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
06ebf18
4 files changed+76 added−4 removed
modified:source/core/Ky.ts+1 added-1 removed
1119 unmodified lines1120 // eslint-disable-next-line no-await-in-loop1121 hookResult = await this.#raceWithTotalTimeout(async () => hook({1122 request: this.request,1123 options: this.#getNormalizedOptions(),1124- error: error as Error,1124+ error: error instanceof Error ? error : new NonError(error),1125 retryCount: this.#retryCount + 1,1126 }));1127 } catch (hookError) {1128 // Preserve the original request error path (`throw error`) so beforeError hooks can still run.164 unmodified linesmodified:source/errors/ForceRetryError.ts+3 added-3 removed
14 unmodified lines15161718192021192021222324257 unmodified lines14 unmodified lines
constructor(options?: ForceRetryOptions) { // Runtime protection: wrap non-Error causes in NonError // TypeScript type is Error for guidance, but JS users can pass anything const cause = options?.cause ? (options.cause instanceof Error ? options.cause : new NonError(options.cause)) : undefined; const cause = options?.cause === undefined ? undefined : (options.cause instanceof Error ? options.cause : new NonError(options.cause));
super( options?.code ? `Forced retry: ${options.code}` : 'Forced retry', cause ? {cause} : undefined,7 unmodified linesmodified:test/hooks.ts+34 added
4145 unmodified lines4146 // Verify original value is accessible via NonError.value4147 t.deepEqual((observedCause as any).value, nonErrorValue);4148 });4149 4150+for (const cause of [0, false, '', null]) {4151+ test(`afterResponse hook preserves falsy retry cause ${JSON.stringify(cause)}`, async t => {4152+ let requestCount = 0;4153+ let observedCause: Error & {value?: unknown} | undefined;4154+4155+ const result = await ky('https://example.com', {4156+ async fetch() {4157+ requestCount++;4158+ return new Response('success');4159+ },4160+ retry: {limit: 1},4161+ hooks: {4162+ afterResponse: [({retryCount}) => {4163+ if (retryCount === 0) {4164+ // JavaScript users can pass non-Error causes.4165+ return ky.retry({delay: 0, cause: cause as any});4166+ }4167+ }],4168+ beforeRetry: [({error}) => {4169+ if (isForceRetryError(error)) {4170+ observedCause = error.cause as typeof observedCause;4171+ }4172+ }],4173+ },4174+ }).text();4175+4176+ t.is(result, 'success');4177+ t.is(requestCount, 2);4178+ t.true(observedCause instanceof Error);4179+ t.is(observedCause?.name, 'NonError');4180+ t.is(observedCause?.value, cause);4181+ });4182+}4183+4184 test('afterResponse hook can retry on 401 status', async t => {4185 let requestCount = 0;4186 4187 const server = await createHttpTestServer(t);2244 unmodified linesmodified:test/retry.ts+38 added
7 unmodified lines8 TimeoutError,9 isKyError,10 isNetworkError,11 } from '../source/index.js';12+import {NonError} from '../source/errors/NonError.js';13 import {createHttpTestServer} from './helpers/create-http-test-server.js';14 import {parseRawBody} from './helpers/parse-body.js';15 import {withPerformance} from './helpers/with-performance.js';16 3385 unmodified lines3402 // 1 initial + 2 retries3403 t.is(fetchCallCount, 3);3404 });3405 3406+for (const thrownValue of [null, 'Temporary failure']) {3407+ test(`beforeRetry wraps non-Error exceptions: ${JSON.stringify(thrownValue)}`, async t => {3408+ let fetchCallCount = 0;3409+ let beforeRetryCallCount = 0;3410+3411+ const result = await ky('https://example.com', {3412+ retry: {3413+ limit: 1,3414+ delay: () => 0,3415+ shouldRetry: () => true,3416+ },3417+ async fetch() {3418+ fetchCallCount++;3419+ if (fetchCallCount === 1) {3420+ // Exercise JavaScript's ability to throw arbitrary values.3421+ // eslint-disable-next-line @typescript-eslint/only-throw-error3422+ throw thrownValue;3423+ }3424+3425+ return new Response('ok');3426+ },3427+ hooks: {3428+ beforeRetry: [({error}) => {3429+ beforeRetryCallCount++;3430+ t.true(error instanceof NonError);3431+ t.is((error as NonError).value, thrownValue);3432+ t.is(typeof error.message, 'string');3433+ }],3434+ },3435+ }).text();3436+3437+ t.is(result, 'ok');3438+ t.is(fetchCallCount, 2);3439+ t.is(beforeRetryCallCount, 1);3440+ });3441+}3442+3443 test('NetworkError is retried by default', async t => {3444 let fetchCallCount = 0;3445 3446 const result = await ky('https://example.com', {526 unmodified lines