Remote Functions - return network error when user is offline
Describe the problem
I want to easily handle network errors, such as when a user clicks a button to perform a client-side query; but since they're offline, I need to handle that and display a user-friendly error.
When the client executes a query remote function, but the user is offline, the response is a 500 error. Here's the code I tested with (the closest real-world example would be a search page):
<script lang="ts">
import { getThing } from './remote.ts'
let thing = $state()
async function getTheThing() {
try {
thing = await getThing()
} catch (e) {
console.error('failed to get thing', e)
}
}
</script>
<button onclick={() => getTheThing()}>Try doing this while offline</button>
<p>Thing is: {thing}</p>In my catch statement, the yielded error is:
failed to get thing HandledHttpError {status: 500, body: {…}}
Describe the proposed solution
When there is no connection to the remote server, ideally provide a Network Error or generic error so that there's a way to do an instanceof check, rather than an HTTP error since the request never went through.
For example:
<script lang="ts">
+ import { NetworkError } from '@sveltejs/kit'
import { getThing } from './remote.ts'
let thing = $state()
async function getTheThing() {
try {
thing = await getThing()
} catch (e) {
console.error('failed to get thing', e)
}
}
</script>
<button onclick={() => getTheThing()}>Try doing this while offline</button>
+<svelte:boundary>
+ {#snippet failed(e)}
+ {#if e instanceof NetworkError}
+ The request failed. Please check your network connection and try again.
+ {/if}
+ {/snippet}
<p>Thing is: {thing}</p>
+</svelte:boundary>I don't have a clever solution to avoid boilerplate, but at least I can build an <ErrorBoundary> component in userland to wrap important markup in my application. Or I could leverage getThing().error elsewhere to handle network errors.
Alternatives considered
Handle the 'Internal error' message and take a guess whether the user was offline or not fully connected at the time the request was made.
Importance
would make my life easier
Additional Information
├── @sveltejs/[email protected]
├── [email protected]
└── [email protected]Source: sveltejs/kit