Skip to content
Myr

Preserve caller stack for schema validation errors (#883)

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 33682a7 · Browse files · 3 files+107 added−17 removed
This commit

State

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

Diff stats

3 files+107 added−17 removed

  • tests:+85 added−0 removed
  • other:+22 added−17 removed

3 files+107 added−17 removed

modified:source/core/Ky.ts+22 added-17 removed
329 unmodified lines
330 : (text === '' && schema !== undefined331 ? undefined332 : JSON.parse(text));333334 if (schema === undefined) {335 return jsonValue;336 }337338 // eslint-disable-next-line no-return-await, @typescript-eslint/return-await -- Awaiting here preserves the caller's async stack when schema validation fails.334 return schema === undefined ? jsonValue : validateJsonWithSchema(jsonValue, schema);339 return await validateJsonWithSchema(jsonValue, schema);340 });341342 if (parsedResult === timedOutOperation) {343 await ky.#throwProcessedError(new TimeoutError(request));
418 unmodified lines
762763 async #raceWithTotalTimeout<T>(operation: () => Promise<T>): Promise<T | typeof timedOutOperation> {764 const remainingTotal = this.#getRemainingTotalTimeout();765 if (remainingTotal === undefined) {766 // eslint-disable-next-line no-return-await, @typescript-eslint/return-await -- Awaiting here preserves the caller's async stack when the operation fails.761 return operation();767 return await operation();768 }769770 if (remainingTotal <= 0) {771 this.#abortController?.abort();
6 unmodified lines
778 timeoutId = setTimeout(() => {779 resolve(timedOutOperation);780 }, remainingTotal);781 });776 const operationResult = Promise.resolve()777 .then(operation)778 .then(value => ({status: 'fulfilled', value} as const))779 .catch((error: unknown) => ({status: 'rejected', error} as const));780 const result = await Promise.race([operationResult, timeoutPromise]);782 const operationPromise = operation();783 const result = await Promise.race([operationPromise, timeoutPromise]);784 const remainingAfterOperation = this.#getRemainingTotalTimeout();785 const didTimeOut = result === timedOutOperation || (remainingAfterOperation !== undefined && remainingAfterOperation <= 0);786 if (didTimeOut) {787 this.#abortController?.abort();788789 if (result === timedOutOperation) {787 void operationResult.then(result => {788 if (result.status === 'fulfilled') {789 this.#cancelReturnedBody(result.value);790 }791 });792 } else if (result.status === 'fulfilled') {793 this.#cancelReturnedBody(result.value);790 void operationPromise.then(value => {791 this.#cancelReturnedBody(value);792 }).catch(() => undefined);793 } else {794 this.#cancelReturnedBody(result);795 }796797 return timedOutOperation;798 }799799 if (result.status === 'rejected') {800 throw result.error;800 return result;801 } catch (error: unknown) {802 const remainingAfterOperation = this.#getRemainingTotalTimeout();803 if (remainingAfterOperation !== undefined && remainingAfterOperation <= 0) {804 this.#abortController?.abort();805 return timedOutOperation;806 }807803 return result.value;808 throw error;809 } finally {810 clearTimeout(timeoutId);811 }812 }
415 unmodified lines
modified:test/hooks.ts+33 added
814 unmodified lines
815 await delay(0);816 t.true(didCancelBody);817});818819test('totalTimeout cancels a hook response produced after the timer wins', async t => {820 let resolveHook: (response: Response) => void;821 let didCancelBody = false;822 let markHookStarted: () => void;823 const hookStarted = new Promise<void>(resolve => {824 markHookStarted = resolve;825 });826827 const request = ky('https://example.com', {828 totalTimeout: 500,829 hooks: {830 beforeRequest: [831 async () => new Promise<Response>(resolve => {832 resolveHook = resolve;833 markHookStarted();834 }),835 ],836 },837 });838839 await hookStarted;840 await t.throwsAsync(request, {instanceOf: TimeoutError});841842 resolveHook(new Response(new ReadableStream({843 cancel() {844 didCancelBody = true;845 },846 })));847 await delay(0);848849 t.true(didCancelBody);850});851852test.serial('totalTimeout takes precedence over a hook error produced after the deadline', async t => {853 const originalPerformanceNow = globalThis.performance.now;854 let currentTime = 0;855 globalThis.performance.now = () => currentTime;
4741 unmodified lines
modified:test/main.ts+52 added
457 unmodified lines
458 t.false(isKyError(error));459 t.deepEqual(error?.issues, issues);460});461462test('.json(schema) keeps the caller in the error stack with and without totalTimeout', async t => {463 const server = await createHttpTestServer(t);464 server.get('/', (_request, response) => {465 response.json({value: 'invalid'});466 });467468 const schema = createSchema<{value: number}>(() => ({issues: [{message: 'Expected {value:number}'}]}));469470 async function schemaValidationCaller(totalTimeout: number | false) {471 const {value} = await ky.get(server.url, {totalTimeout}).json(schema);472 return value;473 }474475 async function schemaValidationEntryPoint(totalTimeout: number | false) {476 await schemaValidationCaller(totalTimeout);477 }478479 for (const totalTimeout of [false, 10_000] as const) {480 // eslint-disable-next-line no-await-in-loop481 const error = await t.throwsAsync(schemaValidationEntryPoint(totalTimeout), {instanceOf: SchemaValidationError});482483 t.regex(error?.stack ?? '', /schemaValidationCaller/);484 t.regex(error?.stack ?? '', /schemaValidationEntryPoint/);485 }486});487488test('.json(schema) preserves async validator errors without aborting the request', async t => {489 let requestSignal: AbortSignal | undefined;490 let validationError: Error | undefined;491 const schema = createSchema(async () => {492 await delay(0);493 validationError = new Error('validate exploded');494 throw validationError;495 });496497 async function asyncValidationCaller() {498 await ky('https://example.com', {499 async fetch(request) {500 requestSignal = request.signal;501 return new Response('{"value":1}');502 },503 totalTimeout: 10_000,504 }).json(schema);505 }506507 const error = await t.throwsAsync(asyncValidationCaller(), {message: 'validate exploded'});508509 t.is(error, validationError);510 t.regex(error?.stack ?? '', /asyncValidationCaller/);511 t.false(requestSignal?.aborted);512});513514test('.json(schema) throws TypeError for invalid schema objects', async t => {515 const server = await createHttpTestServer(t);516 server.get('/', (_request, response) => {517 response.json({value: 1});
2613 unmodified lines