You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
svelte/documentation/docs/05-special-elements/01-svelte-boundary.md

2.6 KiB

title
<svelte:boundary>
<svelte:boundary onerror={handler}>...</svelte:boundary>

[!NOTE] This feature was added in 5.3.0

Boundaries allow you to guard against errors in part of your app from breaking the app as a whole, and to recover from those errors.

If an error occurs while rendering or updating the children of a <svelte:boundary>, or running any $effect functions contained therein, the contents will be removed.

Errors occurring outside the rendering process (for example, in event handlers) are not caught by error boundaries.

Properties

For the boundary to do anything, one or both of failed and onerror must be provided.

failed

If a failed snippet is provided, it will be rendered with the error that was thrown, and a reset function that recreates the contents (demo):

<svelte:boundary>
	<FlakyComponent />

	{#snippet failed(error, reset)}
		<button onclick={reset}>oops! try again</button>
	{/snippet}
</svelte:boundary>

[!NOTE] As with snippets passed to components, the failed snippet can be passed explicitly as a property...

<svelte:boundary {failed}>...</svelte:boundary>

...or implicitly by declaring it directly inside the boundary, as in the example above.

onerror

If an onerror function is provided, it will be called with the same two error and reset arguments. This is useful for tracking the error with an error reporting service...

<svelte:boundary onerror={(e) => report(e)}>
	...
</svelte:boundary>

...or using error and reset outside the boundary itself:

<script>
	let error = $state(null);
	let reset = $state(() => {});

	function onerror(e, r) {
		error = e;
		reset = r;
	}
</script>

<svelte:boundary {onerror}>
	<FlakyComponent />
</svelte:boundary>

{#if error}
	<button onclick={() => {
		error = null;
		reset();
	}}>
		oops! try again
	</button>
{/if}

If an error occurs inside the onerror function (or if you rethrow the error), it will be handled by a parent boundary if such exists.