要防止错误导致你的应用处于损坏状态,你可以使用 <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>
:
<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:
<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
:
<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:
<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.
<script>
import FlakyComponent from './FlakyComponent.svelte';
</script>
<FlakyComponent />