Skip to content
Myr

Preserve abort reasons while reading HTTP error bodies

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 e4269f0 · Browse files · 2 files+40 added−0 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+40 added−0 removed

  • tests:+39 added−0 removed
  • other:+1 added−0 removed

2 files+40 added−0 removed

modified:source/core/Ky.ts+1 added
244 unmodified lines
245 const httpError: HTTPError = new HTTPError(currentResponse, ky.#getResponseRequest(currentResponse), ky.#getNormalizedOptions());246 const errorToThrow: Error = httpError;247 // eslint-disable-next-line no-await-in-loop248 httpError.data = await ky.#getResponseData(currentResponse);249 ky.#throwIfAbortedByUser();250 ky.#throwIfTotalTimeoutExhausted();251252 if (responseFromHook) {253 throw errorToThrow;
1056 unmodified lines
modified:test/http-error.ts+39 added
12 unmodified lines
1314 return response as Response;15}1617for (const useCustomReason of [false, true]) {18 test(`aborting an HTTP error body preserves the abort reason (custom: ${useCustomReason})`, async t => {19 const server = await createHttpTestServer(t);20 const controller = new AbortController();21 const reason = useCustomReason ? new Error('Canceled by the user') : undefined;22 let hookError: Error | undefined;23 let hookCallCount = 0;24 let requestCount = 0;2526 server.get('/', (_request, response) => {27 requestCount++;28 response.status(500).type('application/json');29 response.write('{"error":"');30 });3132 const error = await t.throwsAsync(ky(server.url, {33 signal: controller.signal,34 retry: 0,35 hooks: {36 afterResponse: [() => {37 setTimeout(() => {38 controller.abort(reason);39 }, 0);40 }],41 beforeError: [({error}) => {42 hookError = error;43 hookCallCount++;44 return error;45 }],46 },47 }));4849 t.is(error, controller.signal.reason);50 t.is(hookError, controller.signal.reason);51 t.is(hookCallCount, 1);52 t.is(requestCount, 1);53 });54}5556test('HTTPError handles undefined response.statusText', t => {57 const status = 500;58 // @ts-expect-error missing options59 const error = new HTTPError(
631 unmodified lines