Skip to main content
Basic Svelte
Introduction
Reactivity
Props
Logic
Events
Bindings
Classes and styles
Actions
Transitions
Advanced Svelte
Advanced reactivity
Reusing content
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

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

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.

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>

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>

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>

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>

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

Edit this page on GitHub

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