Skip to content
Myr

Add retry count to `afterResponse` and `beforeError` hooks (#763)

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

authored by Sindre Sorhus · committed by GitHub · parent 5fc5bfb · Browse files · 5 files+163 added−11 removed
This commit

State

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

Diff stats

5 files+163 added−11 removed

  • tests:+79 added−0 removed
  • other:+84 added−11 removed

5 files+163 added−11 removed

modified:source/core/Ky.ts+2 added-1 removed
45 unmodified lines
46 const modifiedResponse = await hook(47 ky.request,48 ky.#getNormalizedOptions(),49 ky._decorateResponse(response.clone()),50 {retryCount: ky._retryCount},51 );5253 if (modifiedResponse instanceof globalThis.Response) {54 response = modifiedResponse;
6 unmodified lines
61 let error = new HTTPError(response, ky.request, ky.#getNormalizedOptions());6263 for (const hook of ky._options.hooks.beforeError) {64 // eslint-disable-next-line no-await-in-loop64 error = await hook(error);65 error = await hook(error, {retryCount: ky._retryCount});66 }6768 throw error;69 }
311 unmodified lines
modified:source/types/hooks.ts+53 added-7 removed
modified:source/index.ts+2 added
50 unmodified lines
51 BeforeRequestState,52 BeforeRetryHook,53 BeforeRetryState,54 BeforeErrorHook,55 BeforeErrorState,56 AfterResponseHook,57 AfterResponseState,58} from './types/hooks.js';5960export type {ResponsePromise} from './types/ResponsePromise.js';61export type {KyRequest} from './types/request.js';
4 unmodified lines
modified:test/hooks.ts+79 added
749 unmodified lines
750 });751752 await server.close();753});754755test('afterResponse hook receives retryCount in state parameter', async t => {756 let requestCount = 0;757 const retryCounts: number[] = [];758759 const server = await createHttpTestServer();760 server.get('/', (_request, response) => {761 requestCount++;762763 if (requestCount <= 2) {764 // First two requests fail765 response.sendStatus(500);766 } else {767 // Third request succeeds768 response.end('success');769 }770 });771772 await ky.get(server.url, {773 retry: {774 limit: 2,775 },776 hooks: {777 afterResponse: [778 (_request, _options, _response, state) => {779 t.is(typeof state.retryCount, 'number');780 retryCounts.push(state.retryCount);781 },782 ],783 },784 });785786 // AfterResponse should be called 3 times (initial + 2 retries)787 t.is(requestCount, 3);788 t.deepEqual(retryCounts, [0, 1, 2]);789790 await server.close();791});792793test('beforeError hook receives retryCount in state parameter', async t => {794 let requestCount = 0;795 let errorRetryCount: number | undefined;796797 const server = await createHttpTestServer();798 server.get('/', (_request, response) => {799 requestCount++;800 // All requests fail801 response.sendStatus(500);802 });803804 try {805 await ky.get(server.url, {806 retry: {807 limit: 2,808 },809 hooks: {810 beforeError: [811 (error: HTTPError, state) => {812 // Verify retryCount exists in state and is a number813 t.is(typeof state.retryCount, 'number');814 t.true(state.retryCount >= 0);815 errorRetryCount = state.retryCount;816 return error;817 },818 ],819 },820 });821 t.fail('Should have thrown an error');822 } catch (error: any) {823 t.true(error instanceof HTTPError);824 // State should have had retryCount = 2 (after 2 retries)825 t.is(errorRetryCount, 2);826 }827828 // Should have made 3 requests total (initial + 2 retries)829 t.is(requestCount, 3);830831 await server.close();832});
modified:readme.md+27 added-3 removed
286 unmodified lines
287Default: `[]`288289This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives an object with the normalized request and options, an error instance, and the retry count. You could, for example, modify `request.headers` here.290291The `retryCount` is always `>= 1` since this hook is only called during retries, not on the initial request.292293If the request received a response, the error will be of type `HTTPError` and the `Response` object will be available at `error.response`. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will not be an instance of `HTTPError`.294295You can prevent Ky from retrying the request by throwing an error. Ky will not handle it in any way and the error will be propagated to the request initiator. The rest of the `beforeRetry` hooks will not be called in this case. Alternatively, you can return the [`ky.stop`](#kystop) symbol to do the same thing but without propagating an error (this has some limitations, see `ky.stop` docs for details).296
16 unmodified lines
313314Type: `Function[]`\315Default: `[]`316315This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives a `HTTPError` as an argument and should return an instance of `HTTPError`.317This hook enables you to modify the `HTTPError` right before it is thrown. The hook function receives a `HTTPError` and a state object as arguments and should return an instance of `HTTPError`.318319The `state.retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between the initial request and retries, which is useful when you need different error handling based on retry attempts (e.g., showing different error messages on the final attempt).320321```js322import ky from 'ky';323324await ky('https://example.com', {
7 unmodified lines
332 error.message = `${body.message} (${response.status})`;333 }334335 return error;336 },337338 // Or show different message based on retry count339 (error, state) => {340 if (state.retryCount === error.options.retry.limit) {341 error.message = `${error.message} (failed after ${state.retryCount} retries)`;342 }343344 return error;345 }346 ]347 }348});
3 unmodified lines
352353Type: `Function[]`\354Default: `[]`355343This hook enables you to read and optionally modify the response. The hook function receives normalized request, options, and a clone of the response as arguments. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).356This hook enables you to read and optionally modify the response. The hook function receives normalized request, options, a clone of the response, and a state object. The return value of the hook function will be used by Ky as the response object if it's an instance of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).357358The `state.retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., showing a notification only on the final retry).359360```js361import ky from 'ky';362363const response = await ky('https://example.com', {
15 unmodified lines
379380 // Retry with the token381 request.headers.set('Authorization', `token ${token}`);382368 return ky(request);383 return ky(request, options);384 }385 },386387 // Or show a notification only on the last retry for 5xx errors388 (request, options, response, {retryCount}) => {389 if (response.status >= 500 && response.status <= 599) {390 if (retryCount === options.retry.limit) {391 showNotification('Request failed after all retries');392 }393 }394 }395 ]396 }397});
441 unmodified lines