Skip to content

Trouble catching fetch errors in module context load #4659

Closed
@stephenlrandall

Description

@stephenlrandall

Describe the bug

Adding module context load functions with fetch attempts to non-existent resources seems to introduce errors that can't be caught. Similar fetch calls in the non-module context script tags can have their errors caught in the expected way:

res = await fetch('/resource/no/exist').catch(err => ...);

Additionally, fetch errors in __layout.svelte specifically will cause an infinite loop as the load function is run over and over again.

Reproduction

In the template SvelteKit to-do application, add something to the effect of:

<script context="module">
	export async function load({ fetch }) {
		console.log("Attempting to fetch...");

		const res = await fetch("/-favicon.png").catch(_ => console.log("Caught an error!"))

		if (res.ok)
			return { status: 200 };
		else
			return {
				status: res.status,
				props: { error: res.statusText }
			};
	}
</script>

If this is in __layout.svelte, the "Attempting to fetch..." line will be printed indefinitely as the load hangs. If this is in a specific route (like the About page), navigation will not hang but the error will also not get caught.

If this fetch is not in module context, the error is caught and the "Caught an error!" line is printed. If the fetch is changed to an existing resource ("-favicon" -> "favicon", for example), everything works fine as well.

Logs

No response

System Info

System:
    OS: macOS 12.3.1
    CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 780.53 MB / 16.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 17.9.0 - /usr/local/bin/node
    npm: 8.5.5 - /usr/local/bin/npm
  Browsers:
    Safari: 15.4
  npmPackages:
    @sveltejs/adapter-auto: next => 1.0.0-next.34 
    @sveltejs/kit: next => 1.0.0-next.314 
    svelte: ^3.46.0 => 3.47.0

Severity

serious, but I can work around it

Additional Information

I can work around this issue by moving the fetch calls into the main script to correctly catch any errors, but this is obviously non-ideal as content will flash/jump as it's loaded in.

Really hoping this is me missing something obvious, and apologies if that's the case! I tried asking about this in the Svelte Discord a couple times but got no response.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions