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
Provenance
- Commit
e68ea7a- Tree
cbcacb1- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
33682a7
3 files changed+107 added−17 removed
modified:source/core/Ky.ts+22 added-17 removed
329 unmodified lines330 : (text === '' && schema !== undefined331 ? undefined332 : JSON.parse(text));333 334+ if (schema === undefined) {335+ return jsonValue;336+ }337+338+ // 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 });341 342 if (parsedResult === timedOutOperation) {343 await ky.#throwProcessedError(new TimeoutError(request));418 unmodified lines762 763 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 }769 770 if (remainingTotal <= 0) {771 this.#abortController?.abort();6 unmodified lines778 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();788 789 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 }796 797 return timedOutOperation;798 }799 799- 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 }807 803- return result.value;808+ throw error;809 } finally {810 clearTimeout(timeoutId);811 }812 }415 unmodified linesmodified:test/hooks.ts+33 added
814 unmodified lines815 await delay(0);816 t.true(didCancelBody);817 });818 819+test('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+ });826+827+ 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+ });838+839+ await hookStarted;840+ await t.throwsAsync(request, {instanceOf: TimeoutError});841+842+ resolveHook(new Response(new ReadableStream({843+ cancel() {844+ didCancelBody = true;845+ },846+ })));847+ await delay(0);848+849+ t.true(didCancelBody);850+});851+852 test.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 linesmodified:test/main.ts+52 added
457 unmodified lines458 t.false(isKyError(error));459 t.deepEqual(error?.issues, issues);460 });461 462+test('.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+ });467+468+ const schema = createSchema<{value: number}>(() => ({issues: [{message: 'Expected {value:number}'}]}));469+470+ async function schemaValidationCaller(totalTimeout: number | false) {471+ const {value} = await ky.get(server.url, {totalTimeout}).json(schema);472+ return value;473+ }474+475+ async function schemaValidationEntryPoint(totalTimeout: number | false) {476+ await schemaValidationCaller(totalTimeout);477+ }478+479+ 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});482+483+ t.regex(error?.stack ?? '', /schemaValidationCaller/);484+ t.regex(error?.stack ?? '', /schemaValidationEntryPoint/);485+ }486+});487+488+test('.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+ });496+497+ 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+ }506+507+ const error = await t.throwsAsync(asyncValidationCaller(), {message: 'validate exploded'});508+509+ t.is(error, validationError);510+ t.regex(error?.stack ?? '', /asyncValidationCaller/);511+ t.false(requestSignal?.aborted);512+});513+514 test('.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