Skip to content
Myr

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

4 files+151 added−13 removed

modified:source/core/Ky.ts+2 added
185 unmodified lines
186 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 lines
modified:source/types/hooks.ts+8 added-6 removed
41 unmodified lines
4243export type AfterResponseHook = (state: AfterResponseState) => Response | RetryMarker | void | Promise<Response | RetryMarker | void>;4445export type BeforeErrorState = {46 request: KyRequest;47 options: NormalizedOptions;4849 // `Error` (not `KyError`) because this receives all errors, including non-Ky ones like network `TypeError`s.50 error: Error;5152 /**
206 unmodified lines
259 */260 afterResponse?: AfterResponseHook[];261262 /**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.264265 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.266267 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 line
269 @default []270271 @example272 ```270 import ky, {isHTTPError, isTimeoutError} from 'ky';273 import ky, {isHTTPError} from 'ky';274275 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 !== null
3 unmodified lines
286 error.message = `${String(error.data.message)} (${error.response.status})`;287 }288 }289287 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);292293 return error;294 }295 ]
6 unmodified lines
modified:test/hooks.ts+136 added-1 removed
6 unmodified lines
7 isTimeoutError,8 isForceRetryError,9 TimeoutError,10} from '../source/index.js';11import {type Options} from '../source/types/options.js';11import {type Options, type NormalizedOptions} from '../source/types/options.js';12import {createHttpTestServer} from './helpers/create-http-test-server.js';1314const withHeader = (request: Request, name: string, value: string) => {15 const headers = new Headers(request.headers);
1927 unmodified lines
1943 t.is(response.status, 500);1944 t.false(hookCalled);1945});19461947test('beforeError receives request and options for HTTPError', async t => {1948 let receivedRequest: Request | undefined;1949 let receivedOptions: NormalizedOptions | undefined;19501951 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 );19681969 t.true(receivedRequest?.url.includes('example.com'));1970 t.is(receivedOptions?.method, 'GET');1971});19721973test('beforeError receives request and options for network TypeError', async t => {1974 let receivedRequest: Request | undefined;1975 let receivedOptions: NormalizedOptions | undefined;19761977 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 );19941995 t.true(receivedRequest?.url.includes('example.com'));1996 t.is(receivedOptions?.method, 'GET');1997});19981999test('beforeError receives request and options for TimeoutError', async t => {2000 let receivedRequest: Request | undefined;2001 let receivedOptions: NormalizedOptions | undefined;20022003 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 );20222023 t.true(receivedRequest?.url.includes('example.com'));2024 t.is(receivedOptions?.method, 'GET');2025});20262027test('beforeError receives options.context', async t => {2028 let receivedContext: unknown;20292030 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 );20472048 t.deepEqual(receivedContext, {userId: '123', action: 'test'});2049});20502051test('beforeError receives request and options when beforeRequest hook throws', async t => {2052 let receivedRequest: Request | undefined;2053 let receivedOptions: NormalizedOptions | undefined;20542055 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 );20772078 t.true(receivedRequest?.url.includes('example.com'));2079 t.is(receivedOptions?.method, 'GET');2080});20812082test('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 lines
modified:readme.md+5 added-6 removed
520 unmodified lines
521522Type: `Function[]`\523Default: `[]`524525This 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.525This 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.526527This 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.528529The `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).530531```js532import ky, {isHTTPError, isTimeoutError} from 'ky';532import ky, {isHTTPError} from 'ky';533534await 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 !== null
3 unmodified lines
545 error.message = `${String(error.data.message)} (${error.response.status})`;546 }547 }548549 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);551552 return error;553 }554 ]
946 unmodified lines