為了防止錯誤使你的應用程式處於損壞狀態,你可以使用 <svelte:boundary>
元素將它們包含在錯誤邊界內。
在這個範例中,<FlakyComponent>
包含一個錯誤 — 點擊按鈕會將 mouse
設定為 null
,這意味著範本中的 {mouse.x}
和 {mouse.y}
表達式將無法呈現。
在理想情況下,我們應該直接修復錯誤。但這並不總是可行的 — 有時元件屬於其他人,有時你只是需要防範意外。首先用 <svelte:boundary>
包裹 <FlakyComponent />
App
<svelte:boundary>
<FlakyComponent />
</svelte:boundary>
到目前為止,沒有任何改變,因為邊界沒有指定處理程式。新增一個 failed
程式碼片段,以在發生錯誤時顯示一些 UI
App
<svelte:boundary>
<FlakyComponent />
{#snippet failed(error)}
<p>Oops! {error.message}</p>
{/snippet}
</svelte:boundary>
現在,當我們點擊按鈕時,邊界的內容會被程式碼片段取代。我們可以嘗試使用傳遞給 failed
的第二個參數來重設
App
<svelte:boundary>
<FlakyComponent />
{#snippet failed(error, reset)}
<p>Oops! {error.message}</p>
<button onclick={reset}>Reset</button>
{/snippet}
</svelte:boundary>
我們也可以指定一個 onerror
處理程式,它會使用傳遞給 failed
程式碼片段的相同參數來呼叫
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 非常有用。
上一個 下一個
1
2
3
4
5
6
<script>
import FlakyComponent from './FlakyComponent.svelte';
</script>
<FlakyComponent />