37
loading...
This website collects cookies to deliver better user experience
npm i @crownframework/svelte-error-boundary
Boundary
avoids crashing the Svelte application. (See REPL here.)<!-- User.svelte -->
<script>
import { Boundary } from '@crownframework/svelte-error-boundary';
const user = null;
</script>
<!-- The code inside this boundary will throw immediately -->
<Boundary onError={console.error}>
{user.name}
</Boundary>
onError
attribute can be used to perform additional error logging, such as to the console or to an external service like Sentry.<slot>
for where the non-error content should be placed. Let's make an error component based on the default component that the package provides. We will also style it ourselves:<!-- UserError.svelte -->
<script>
export let error = null;
export let onError = null;
$: if ($error && onError) onError($error);
</script>
{#if $error}
<div class="error">
<em>User could not be shown</em>
</div>
{:else}
<slot />
{/if}
<style>
.error {
background-color: #666;
color: white;
padding: 10px;
}
</style>
User.svelte
component and convert it to an error boundary using the createBoundary
function:<!-- User.svelte -->
<script>
import UserError from './UserError.svelte';
import { createBoundary } from '@crownframework/svelte-error-boundary';
const user = null;
const Boundary = createBoundary(UserError);
</script>
<!-- The code inside this boundary will throw immediately -->
<Boundary onError={console.error}>
{user.name}
</Boundary>
{:catch error}
.