Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

要防止错误导致你的应用处于损坏状态,你可以使用 <svelte:boundary> 元素将它们包含在错误边界内。

¥To prevent errors from leaving your app in a broken state, you can contain them inside an error boundary using the <svelte:boundary> element.

在此示例中,<FlakyComponent> 包含一个错误 — 单击按钮会将 mouse 设置为 null,这意味着模板中的 {mouse.x}{mouse.y} 表达式将无法渲染。

¥In this example, <FlakyComponent> contains a bug — clicking the button will set mouse to null, meaning that the {mouse.x} and {mouse.y} expressions in the template will fail to render.

在理想情况下,我们只需修复该错误即可。但这并不总是一种选择 - 有时组件属于其他人,有时你只需要防范意外情况。首先用 <svelte:boundary> 封装 <FlakyComponent />

¥In an ideal world we’d simply fix the bug. But that’s not always an option — sometimes the component belongs to someone else, and sometimes you just need to guard against the unexpected. Begin by wrapping <FlakyComponent /> with <svelte:boundary>:

App
<svelte:boundary>
	<FlakyComponent />
</svelte:boundary>

到目前为止,没有任何变化,因为边界没有指定处理程序。添加 failed snippet 以提供一些 UI 来显示发生错误时的情况:

¥So far, nothing has changed, because the boundary doesn’t specify a handler. Add a failed snippet to provide some UI to show when an error occurs:

App
<svelte:boundary>
	<FlakyComponent />

	{#snippet failed(error)}
		<p>Oops! {error.message}</p>
	{/snippet}
</svelte:boundary>

现在,当我们单击按钮时,边界的内容将替换为代码片段。我们可以尝试通过使用传递给 failed 的第二个参数来重置事物:

¥Now, when we click the button, the contents of the boundary are replaced with the snippet. We can attempt to reset things by making use of the second argument passed to failed:

App
<svelte:boundary>
	<FlakyComponent />

	{#snippet failed(error, reset)}
		<p>Oops! {error.message}</p>
		<button onclick={reset}>Reset</button>
	{/snippet}
</svelte:boundary>

我们还可以指定一个 onerror 处理程序,使用传递给 failed 代码段的相同参数调用它:

¥We can also specify an onerror handler, which is called with the same arguments passed to the failed snippet:

App
<svelte:boundary onerror={(e) => console.error(e)}>
	<FlakyComponent />

	{#snippet failed(error, reset)}
		<p>Oops! {error.message}</p>
		<button onclick={reset}>Reset</button>
	{/snippet}
</svelte:boundary>

这对于将有关错误的信息发送到报告服务或在错误边界之外添加 UI 非常有用。

¥This is useful for sending information about the error to a reporting service, or adding UI outside the error boundary itself.

上一页 下一页
1
2
3
4
5
6
<script>
	import FlakyComponent from './FlakyComponent.svelte';
</script>
 
<FlakyComponent />