Skip to main content

<svelte:boundary>

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

此功能已在 5.3.0 中添加

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

如果在渲染或更新 <svelte:boundary> 的子项或运行其中包含的任何 $effect 函数时发生错误,则将删除内容。

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

¥Properties

要使边界执行任何操作,必须提供 failedonerror 中的一个或两个。

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

failed

如果提供了 failed 代码片段,它将与抛出的错误一起渲染,并重新创建内容的 reset 函数(demo):

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

传递给组件的代码片段 一样,failed 代码片段可以作为属性明确传递...

¥[!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`

如果提供了 `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.