Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/calm-bats-query.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

fix: preserve remote query transport errors
Original file line number Diff line number Diff line change
Expand Up @@ -104,19 +104,32 @@ describe('Query errors', () => {
const first_result = Promise.resolve(query);
await tick();
const second_result = query.refresh();
second.reject(new Error('nope'));
const failure = new TypeError('Failed to fetch');
second.reject(failure);

const [first_error, second_error] = await Promise.all([
first_result.catch((error) => error),
second_result.catch((error) => error)
]);
expect(first_error).toBeInstanceOf(HandledHttpError);
expect(second_error).toBeInstanceOf(HandledHttpError);
expect(first_error.body).toBe(second_error.body);
expect(first_error).toBe(failure);
expect(second_error).toBe(failure);
expect(query.error).toEqual({ message: 'Failed to fetch', status: 500 });
expect(query.ready).toBe(false);
expect(query.current).toBeUndefined();
});

test('HTTP failures are finalized after passing through handleError', async () => {
const failure = new HttpError({ status: 503, message: 'unavailable' });
const query = new Query('http-error', () => Promise.reject(failure));

const rejection = await Promise.resolve(query).catch((error) => error);

expect(rejection).toBeInstanceOf(HandledHttpError);
expect(rejection).not.toBe(failure);
expect(rejection.body).toEqual({ status: 503, message: 'unavailable' });
expect(query.error).toEqual({ status: 503, message: 'unavailable' });
});

test('fail rejects existing awaiters before the first value', async () => {
const pending = Promise.withResolvers();
const query = new Query('fail', () => pending.promise);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/** @import { HttpError } from '@sveltejs/kit' */
import { query_responses, handle_error } from '../../client.js';
import { HandledHttpError } from '@sveltejs/kit/internal';
import { HandledHttpError, HttpError } from '@sveltejs/kit/internal';
import { QUERY_OVERRIDE_KEY } from '../shared.svelte.js';
import { noop } from '../../../../utils/functions.js';
import { with_resolvers } from '../../../../utils/promise.js';
Expand Down Expand Up @@ -41,6 +40,8 @@ export class Query {

/** @type {App.Error | undefined} */
#error = $state.raw(undefined);
/** @type {{ value: unknown } | undefined} */
#rejection = $state.raw();

/** @type {Promise<T>['then']} */
// @ts-expect-error TS doesn't understand that the promise returns something
Expand All @@ -51,6 +52,8 @@ export class Query {
return (resolve, reject) => {
const result = p.then(tick).then(() => {
if (!this.#ready) {
if (this.#rejection) throw this.#rejection.value;

throw new HandledHttpError(
this.#error ?? { status: 500, message: 'Query resolved without a value' }
);
Expand Down Expand Up @@ -132,6 +135,7 @@ export class Query {
this.#loading = false;
this.#raw = value;
this.#error = undefined;
this.#rejection = undefined;
});
})
.catch(async (e) => {
Expand All @@ -147,6 +151,7 @@ export class Query {
route: { id: null },
url: new URL(location.href)
});
const rejection = e instanceof HttpError ? new HandledHttpError(error) : e;

// Re-check after the async `handle_error` gap: a later request may have
// resolved/rejected while we were awaiting and superseded this one, so
Expand All @@ -158,10 +163,11 @@ export class Query {
this.#latest.splice(0, idx).forEach((r) => r(undefined));
this.#latest.shift();
this.#error = error;
this.#rejection = { value: rejection };
this.#loading = false;
});

reject(new HandledHttpError(error));
reject(rejection);
});

return promise;
Expand Down Expand Up @@ -249,6 +255,7 @@ export class Query {
this.#ready = true;
this.#loading = false;
this.#error = undefined;
this.#rejection = undefined;
this.#raw = value;

if (!in_flight) {
Expand All @@ -265,6 +272,7 @@ export class Query {
this.#clear_pending();
this.#loading = false;
this.#error = error.body;
this.#rejection = { value: error };

const promise = Promise.reject(error);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@
<script>
import { get_slow_data } from './data.remote.js';
import { isHttpError } from '@sveltejs/kit';
import { get_slow_data, get_thing } from './data.remote.js';

// the query is kicked off during SSR (via the `loading` property access)
// but not awaited, so SSR renders the loading state. The client must
// fetch the data itself after hydration.
const slow = get_slow_data();

let transport_error = $state();

async function fetch_thing() {
try {
await get_thing(Date.now());
} catch (error) {
const is_http_error = isHttpError(error);

transport_error = {
name: error?.constructor.name,
is_http_error,
status: is_http_error ? error.status : null
};
}
}

function delayed_value() {
return new Promise((resolve) => setTimeout(() => resolve('hydrated'), 500));
}
Expand All @@ -20,3 +37,6 @@
<!-- this keeps hydration unsettled long enough for the slow query to
read from the hydration cache rather than it being reset first -->
<p id="other">{await delayed_value()}</p>

<button onclick={fetch_thing}>Fetch thing</button>
<pre id="transport-error">{JSON.stringify(transport_error)}</pre>
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ export const get_slow_data = query(async () => {
await new Promise((resolve) => setTimeout(resolve, 1000));
return 'slow data';
});

export const get_thing = query('unchecked', (value) => value);
15 changes: 15 additions & 0 deletions packages/kit/test/apps/async/test/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,21 @@ test.describe('remote functions', () => {
expect(response.headers()['cache-control']).toBe('private, no-store');
});

test('remote queries preserve network errors', async ({ page, context }) => {
await page.goto('/remote/query-loading-state');
await context.setOffline(true);

try {
await page.getByRole('button', { name: 'Fetch thing' }).click();

await expect(page.locator('#transport-error')).toHaveText(
JSON.stringify({ name: 'TypeError', is_http_error: false, status: null })
);
} finally {
await context.setOffline(false);
}
});

test('clicking a link to the current page refreshes active queries', async ({ page }) => {
await page.goto('/remote/link-refresh');
await page.locator('#reset').click();
Expand Down
Loading