Skip to content
Myr

Name the request that was sent on every `TimeoutError`

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 8a3a9cf · Browse files · 2 files+55 added−10 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+55 added−10 removed

  • tests:+39 added−0 removed
  • other:+16 added−10 removed

2 files+55 added−10 removed

modified:source/core/Ky.ts+16 added-10 removed
399 unmodified lines
400 result[type] = async (schema?: StandardSchemaV1) => {401 // `#fetch()` replaces `ky.request` with the clone it prepares for a possible retry, so a shortcut called402 // after the request was dispatched would otherwise advertise its media type on that clone, which is only403 // sent if a retry happens, instead of on the attempt that produced the response.404 const acceptRequest = ky.#originalRequest ?? ky.request;404 const acceptRequest = ky.#sentRequest;405 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing406 acceptRequest.headers.set('accept', acceptRequest.headers.get('accept') || mimeType);407408 const response = await result;
317 unmodified lines
726 if (shouldRetry !== undefined) {727 const result = await this.#raceWithTotalTimeout(async () => shouldRetry({error: errorObject, retryCount: this.#retryCount + 1}), this.#userProvidedAbortSignal);728 this.#throwIfAbortedByUser();729 if (result === timedOutOperation) {730 throw new TimeoutError(this.request);730 throw new TimeoutError(this.#sentRequest);731 }732733 // Only exact booleans override the default retry checks.734 if (result === false) {
66 unmodified lines
801 }802803 // Defaults to the last request that was actually sent, because `this.request` is the clone `#fetch()` prepares804 // for a possible retry and may never be sent at all.805 async #throwProcessedError(error: unknown, request: Request = this.#originalRequest ?? this.request): Promise<never> {805 async #throwProcessedError(error: unknown, request: Request = this.#sentRequest): Promise<never> {806 // Non-Error throws (e.g., thrown strings) pass through unchanged. `isError` reads the internal brand, so an807 // error from another realm still runs the hooks, the same way the Ky type guards accept branded errors.808 if (!isError(error)) {809 throw error;
86 unmodified lines
896 #getEffectiveTimeout(): number | undefined {897 const remainingTotal = this.#getRemainingTotalTimeout();898 if (remainingTotal !== undefined) {899 if (remainingTotal <= 0) {900 throw new TimeoutError(this.request);900 throw new TimeoutError(this.#sentRequest);901 }902903 return this.#options.timeout === false904 ? remainingTotal
288 unmodified lines
1193 ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController!.signal])1194 : this.#abortController!.signal;1195 }11961197 // `#fetch()` replaces `this.request` with the clone it prepares for a possible retry, so anything reporting the1198 // request that produced a response or failed has to use the one that was actually sent.1199 get #sentRequest(): Request {1200 return this.#originalRequest ?? this.request;1201 }12021197 #throwIfTotalTimeoutExhausted(request: Request = this.request): void {1203 #throwIfTotalTimeoutExhausted(request: Request = this.#sentRequest): void {1204 const remaining = this.#getRemainingTotalTimeout();1205 if (remaining !== undefined && remaining <= 0) {1206 throw new TimeoutError(request);1207 }
8 unmodified lines
1216 retryCount: 0,1217 }), this.#userProvidedAbortSignal);12181219 if (result === timedOutOperation) {1214 throw new TimeoutError(this.request);1220 throw new TimeoutError(this.#sentRequest);1221 }12221223 if (isRequestInstance(result)) {1224 this.#assignRequest(this.#withManagedSignal(result));
26 unmodified lines
1251 retryCount: this.#retryCount,1252 }), this.#userProvidedAbortSignal);12531254 if (modifiedResponse === timedOutOperation) {1249 throw new TimeoutError(this.request);1255 throw new TimeoutError(this.#sentRequest);1256 }1257 } catch (error) {1258 // Cancel both responses to prevent memory leaks when hook throws1259 if (hookResponse !== response) {
55 unmodified lines
13151316 const remainingTimeout = this.#getRemainingTotalTimeout();1317 if (remainingTimeout !== undefined) {1318 if (remainingTimeout <= 0) {1313 throw new TimeoutError(this.request);1319 throw new TimeoutError(this.#sentRequest);1320 }13211322 // If waiting would consume all remaining budget, time out without starting another request.1323 if (retryDelay >= remainingTimeout) {1324 await delay(remainingTimeout, delayOptions);1319 throw new TimeoutError(this.request);1325 throw new TimeoutError(this.#sentRequest);1326 }1327 }13281329 // Only use user-provided signal for delay, not our internal abortController
36 unmodified lines
1366 throw hookError;1367 }13681369 if (hookResult === timedOutOperation) {1364 throw new TimeoutError(this.request);1370 throw new TimeoutError(this.#sentRequest);1371 }13721373 if (isRequestInstance(hookResult)) {1374 // Same contract as `ky.retry({request})`: a Request returned from `beforeRetry`
182 unmodified lines
modified:test/retry.ts+39 added
5095 unmodified lines
50965097 t.is(Object.getPrototypeOf(context), Object.prototype);5098 t.deepEqual(context, {b: 2});5099});51005101// `#fetch()` replaces `ky.request` with the clone it prepares for a possible retry, so a `TimeoutError` built after the request went out reported a request that was never sent, disagreeing with the `request` the `beforeError` hook is given. `#getResponseRequest()` already had the same contract for `HTTPError`.5102test('a TimeoutError names the request that was actually sent', async t => {5103 let sentRequest: Request | undefined;5104 let attempts = 0;51055106 const error = await t.throwsAsync(ky.post('https://example.com', {5107 body: 'payload',5108 retry: {limit: 2, delay: () => 5000, methods: ['post']},5109 totalTimeout: 30,5110 async fetch(request) {5111 attempts++;5112 sentRequest = request;5113 return new Response('server error', {status: 500});5114 },5115 }).text(), {name: 'TimeoutError'});51165117 t.is(attempts, 1, 'the retry delay should have been cut short by the total timeout');5118 t.truthy(sentRequest);5119 t.is((error as {request: Request}).request, sentRequest);5120});51215122test('a TimeoutError raised while retrying names the request that was actually sent', async t => {5123 const sentRequests: Request[] = [];5124 let attempts = 0;51255126 const error = await t.throwsAsync(ky.get('https://example.com', {5127 retry: {limit: 10, delay: () => 30},5128 totalTimeout: 250,5129 async fetch(request) {5130 attempts++;5131 sentRequests.push(request);5132 return new Response('server error', {status: 500});5133 },5134 }).text(), {name: 'TimeoutError'});51355136 t.true(attempts > 1, `the request should have been retried before the budget ran out, got ${attempts}`);5137 t.is((error as {request: Request}).request, sentRequests.at(-1));5138});