Skip to content
Myr

Run beforeError hooks for body reader failures

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 a8753dc · Browse files · 2 files+54 added−1 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+54 added−1 removed

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

2 files+54 added−1 removed

modified:source/core/Ky.ts+1 added-1 removed
787 unmodified lines
788 if (isRawNetworkError(error)) {789 await this.#throwProcessedError(new NetworkError(this.#getResponseRequest(response), {cause: error as Error}));790 }791792 throw error;792 await this.#throwProcessedError(error);793 }794795 result = timedOutResponseData;796 }
502 unmodified lines
modified:test/response-consumption.ts+53 added
179 unmodified lines
180181 t.deepEqual(Buffer.from(buffer), binary);182 t.is(parserCalls, 0);183});184185test('formData parsing errors pass through beforeError exactly once without retrying', async t => {186 const server = await createHttpTestServer(t);187 let requests = 0;188 server.get('/', (_request, response) => {189 requests++;190 response.set('content-type', 'application/json').end('{}');191 });192 const replacement = new Error('Unexpected response format');193 let hookCalls = 0;194195 await t.throwsAsync(ky(server.url, {196 hooks: {197 beforeError: [({error, request, retryCount}) => {198 hookCalls++;199 t.true(error instanceof TypeError);200 t.is(request.url, `${server.url}/`);201 t.is(retryCount, 0);202 return replacement;203 }],204 },205 }).formData(), {is: replacement});206 t.is(hookCalls, 1);207 t.is(requests, 1);208});209210test('beforeError failures while handling body-reader errors propagate without running hooks again', async t => {211 const readError = new Error('Response body could not be read');212 const hookError = new Error('Error handler failed');213 let fetchCalls = 0;214 let hookCalls = 0;215216 await t.throwsAsync(ky('https://example.com', {217 async fetch() {218 fetchCalls++;219 return new Response(new ReadableStream({220 start(controller) {221 controller.error(readError);222 },223 }));224 },225 hooks: {226 beforeError: [({error}) => {227 hookCalls++;228 t.is(error, readError);229 throw hookError;230 }],231 },232 }).text(), {is: hookError});233234 t.is(fetchCalls, 1);235 t.is(hookCalls, 1);236});