Skip to main content

<svelte:boundary>

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

此功能已添加到 5.3.0 版本。

边界允许你对应用的某些部分进行 ‘隔离’ 操作,以便:

¥Boundaries allow you to ‘wall off’ parts of your app, so that you can:

  • 提供在 await 表达式首次解析时应显示的 UI

    ¥provide UI that should be shown when await expressions are first resolving

  • 处理渲染期间或运行效果时发生的错误,并提供发生错误时应渲染的 UI

    ¥handle errors that occur during rendering or while running effects, and provide UI that should be rendered when an error happens

如果边界处理错误(使用 failed 代码片段或 onerror 处理程序,或两者兼有),其现有内容将被删除。

¥If a boundary handles an error (with a failed snippet or onerror handler, or both) its existing content will be removed.

渲染进程之外发生的错误(例如,在事件处理程序中或在 setTimeout 或异步工作之后)不会被错误边界捕获。

属性(Properties)

¥Properties

要使边界执行任何操作,必须提供以下一项或多项。

¥For the boundary to do anything, one or more of the following must be provided.

pending

此代码片段将在首次创建边界时显示,并一直可见,直到边界内的所有 await 表达式都解析完毕(demo):

¥This snippet will be shown when the boundary is first created, and will remain visible until all the await expressions inside the boundary have resolved (demo):

<svelte:boundary>
	<p>{await delayed('hello!')}</p>

	{#snippet pending()}
		<p>loading...</p>
	{/snippet}
</svelte:boundary>

pending 代码段将不会显示在后续的异步更新中 - 对于这些更新,你可以使用 $effect.pending()

¥The pending snippet will not be shown for subsequent async updates — for these, you can use $effect.pending().

playground 中,你的应用会在一个带有空的待处理代码片段的边界内渲染,因此你无需创建 await 代码片段即可使用 await

failed

如果提供了 failed 代码片段,则当边界内发生错误时,它将与 error 和重新创建内容的 reset 函数一起渲染(demo):

¥If a failed snippet is provided, it will be rendered when an error is thrown inside the boundary, with the error 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>

snippets passed to components 一样,failed 代码片段可以显式作为属性传递……

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


>
> ……或者像上面的例子一样,通过在边界内直接声明它来隐式地实现。



### `onerror`

如果提供了 `onerror` 函数,它将使用相同的两个 `error` 和 `reset` 参数进行调用。这对于使用错误报告服务跟踪错误很有用...

¥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
<svelte:boundary onerror={(e) => report(e)}>
	...
</svelte:boundary>

...或在边界本身之外使用 errorreset

¥...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}

如果在 onerror 函数内部发生错误(或者你重新抛出错误),它将由父边界(如果存在)处理。

¥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.