Add `request` and `options` to `beforeError` hook state (#835)
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 90c6d00 · Browse files · 4 files·+151 added−13 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+151 added−13 removed
- tests:+136 added−1 removed
- other:+15 added−12 removed
Provenance
- Commit
01e0b85- Tree
3398ca1- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
90c6d00
4 files changed+151 added−13 removed
modified:source/core/Ky.ts+2 added
185 unmodified lines186 let processedError: Error = error;187 for (const hook of ky.#options.hooks.beforeError) {188 // eslint-disable-next-line no-await-in-loop189 const hookResult: unknown = await hook({190+ request: ky.request,191+ options: ky.#getNormalizedOptions(),192 error: processedError,193 retryCount: ky.#retryCount,194 });195 670 unmodified linesmodified:source/types/hooks.ts+8 added-6 removed
41 unmodified lines42 43 export type AfterResponseHook = (state: AfterResponseState) => Response | RetryMarker | void | Promise<Response | RetryMarker | void>;44 45 export type BeforeErrorState = {46+ request: KyRequest;47+ options: NormalizedOptions;48+49 // `Error` (not `KyError`) because this receives all errors, including non-Ky ones like network `TypeError`s.50 error: Error;51 52 /**206 unmodified lines259 */260 afterResponse?: AfterResponseHook[];261 262 /**260- This hook enables you to modify any error right before it is thrown. The hook function receives a state object with an error and retry count, and should return an `Error` instance.263+ This hook enables you to modify any error right before it is thrown. The hook function receives a state object with the request, options, error, and retry count, and should return an `Error` instance.264 265 This hook is called for all error types, including `HTTPError`, `TimeoutError`, `ForceRetryError` (when retry limit is exceeded via `ky.retry()`), and network errors. Use type guards like `isHTTPError()` or `isTimeoutError()` to handle specific error types.266 267 The `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).1 unmodified line269 @default []270 271 @example272 ```270- import ky, {isHTTPError, isTimeoutError} from 'ky';273+ import ky, {isHTTPError} from 'ky';274 275 await ky('https://example.com', {276 hooks: {277 beforeError: [275- ({error}) => {278+ ({request, options, error}) => {279 if (isHTTPError(error)) {280 if (281 typeof error.data === 'object'282 && error.data !== null3 unmodified lines286 error.message = `${String(error.data.message)} (${error.response.status})`;287 }288 }289 287- if (isTimeoutError(error)) {288- error.message = `Request to ${error.request.url} timed out`;289- }290+ // `request` and `options` are always available291+ console.log(`Request to ${request.url} failed`, options.context);292 293 return error;294 }295 ]6 unmodified linesmodified:test/hooks.ts+136 added-1 removed
6 unmodified lines7 isTimeoutError,8 isForceRetryError,9 TimeoutError,10 } from '../source/index.js';11-import {type Options} from '../source/types/options.js';11+import {type Options, type NormalizedOptions} from '../source/types/options.js';12 import {createHttpTestServer} from './helpers/create-http-test-server.js';13 14 const withHeader = (request: Request, name: string, value: string) => {15 const headers = new Headers(request.headers);1927 unmodified lines1943 t.is(response.status, 500);1944 t.false(hookCalled);1945 });1946 1947+test('beforeError receives request and options for HTTPError', async t => {1948+ let receivedRequest: Request | undefined;1949+ let receivedOptions: NormalizedOptions | undefined;1950+1951+ await t.throwsAsync(1952+ ky('https://example.com', {1953+ retry: 0,1954+ async fetch() {1955+ return new Response('', {status: 500});1956+ },1957+ hooks: {1958+ beforeError: [1959+ ({request, options, error}) => {1960+ receivedRequest = request;1961+ receivedOptions = options;1962+ return error;1963+ },1964+ ],1965+ },1966+ }),1967+ );1968+1969+ t.true(receivedRequest?.url.includes('example.com'));1970+ t.is(receivedOptions?.method, 'GET');1971+});1972+1973+test('beforeError receives request and options for network TypeError', async t => {1974+ let receivedRequest: Request | undefined;1975+ let receivedOptions: NormalizedOptions | undefined;1976+1977+ await t.throwsAsync(1978+ ky('https://example.com', {1979+ retry: 0,1980+ async fetch() {1981+ throw new TypeError('Failed to fetch');1982+ },1983+ hooks: {1984+ beforeError: [1985+ ({request, options, error}) => {1986+ receivedRequest = request;1987+ receivedOptions = options;1988+ return error;1989+ },1990+ ],1991+ },1992+ }),1993+ );1994+1995+ t.true(receivedRequest?.url.includes('example.com'));1996+ t.is(receivedOptions?.method, 'GET');1997+});1998+1999+test('beforeError receives request and options for TimeoutError', async t => {2000+ let receivedRequest: Request | undefined;2001+ let receivedOptions: NormalizedOptions | undefined;2002+2003+ await t.throwsAsync(2004+ ky('https://example.com', {2005+ timeout: 1,2006+ retry: 0,2007+ async fetch() {2008+ await delay(100);2009+ return new Response('ok');2010+ },2011+ hooks: {2012+ beforeError: [2013+ ({request, options, error}) => {2014+ receivedRequest = request;2015+ receivedOptions = options;2016+ return error;2017+ },2018+ ],2019+ },2020+ }),2021+ );2022+2023+ t.true(receivedRequest?.url.includes('example.com'));2024+ t.is(receivedOptions?.method, 'GET');2025+});2026+2027+test('beforeError receives options.context', async t => {2028+ let receivedContext: unknown;2029+2030+ await t.throwsAsync(2031+ ky('https://example.com', {2032+ retry: 0,2033+ context: {userId: '123', action: 'test'},2034+ async fetch() {2035+ return new Response('', {status: 500});2036+ },2037+ hooks: {2038+ beforeError: [2039+ ({options, error}) => {2040+ receivedContext = options.context;2041+ return error;2042+ },2043+ ],2044+ },2045+ }),2046+ );2047+2048+ t.deepEqual(receivedContext, {userId: '123', action: 'test'});2049+});2050+2051+test('beforeError receives request and options when beforeRequest hook throws', async t => {2052+ let receivedRequest: Request | undefined;2053+ let receivedOptions: NormalizedOptions | undefined;2054+2055+ await t.throwsAsync(2056+ ky('https://example.com', {2057+ retry: 0,2058+ async fetch() {2059+ return new Response('ok');2060+ },2061+ hooks: {2062+ beforeRequest: [2063+ () => {2064+ throw new Error('beforeRequest failed');2065+ },2066+ ],2067+ beforeError: [2068+ ({request, options, error}) => {2069+ receivedRequest = request;2070+ receivedOptions = options;2071+ return error;2072+ },2073+ ],2074+ },2075+ }),2076+ );2077+2078+ t.true(receivedRequest?.url.includes('example.com'));2079+ t.is(receivedOptions?.method, 'GET');2080+});2081+2082 test('beforeRequest hook can return modified Request with new URL', async t => {2083 const server = await createHttpTestServer(t);2084 server.get('/', (request, response) => {2085 if (request.query.token === 'secret') {2186 unmodified linesmodified:readme.md+5 added-6 removed
520 unmodified lines521 522 Type: `Function[]`\523 Default: `[]`524 525-This hook enables you to modify any error right before it is thrown. The hook function receives a state object with an error and retry count, and should return an `Error` instance.525+This hook enables you to modify any error right before it is thrown. The hook function receives a state object with the request, options, error, and retry count, and should return an `Error` instance.526 527 This hook is called for all error types, including `HTTPError`, `TimeoutError`, `ForceRetryError` (when retry limit is exceeded via `ky.retry()`), and network errors. Use type guards like `isHTTPError()` or `isTimeoutError()` to handle specific error types.528 529 The `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).530 531 ```js532-import ky, {isHTTPError, isTimeoutError} from 'ky';532+import ky, {isHTTPError} from 'ky';533 534 await ky('https://example.com', {535 hooks: {536 beforeError: [537- ({error}) => {537+ ({request, options, error}) => {538 if (isHTTPError(error)) {539 if (540 typeof error.data === 'object'541 && error.data !== null3 unmodified lines545 error.message = `${String(error.data.message)} (${error.response.status})`;546 }547 }548 549- if (isTimeoutError(error)) {550- error.message = `Request to ${error.request.url} timed out`;551- }549+ // `request` and `options` are always available550+ console.log(`Request to ${request.url} failed`, options.context);551 552 return error;553 }554 ]946 unmodified lines