How to avoid exceptions to freeze entire app in Svelte?
Asked Answered
D

3

12

I'm wondering if there is a way to avoid exceptions to freeze entire Svelte app?

I'm currently using Svelte v3.12.0 and it looks like if there is an uncaught exception, the entire front end app just freeze and it doesn't recover from errors. I do NOT think wrapping every line of code in every component in try...catch... is a good solution for it.

Desolate answered 11/11, 2019 at 5:52 Comment(0)
C
3

You could add an event listener to unhandledrejection and error in your onMount method and then call event.preventDefault() to stop the error event from bubbling, which "traps" the error instead of allowing it to throw.

In your App.svelte (Svelte) or your root +layout.svelte (SvelteKit) you could, for example, handle an unhandled error and show a "toast" notification, show an alert or otherwise handle the error in a more elegant way.

<script lang="ts">
  import { onMount } from 'svelte'
  import { toasts } from '$lib/stores/toasts'

  onMount(() => {
    const report_error = (msg: string = 'unknown error') => {
      toasts.push({
        message: `Unhandled error: ${msg}`,
        type: 'error',
      })
    }

    const handle_rejection = (e: PromiseRejectionEvent) => {
      e.preventDefault()
      report_error(e?.reason)
    }

    const handle_error = (e: ErrorEvent) => {
      e.preventDefault()
      report_error(e?.message)
    }

    window.addEventListener('unhandledrejection', handle_rejection)
    window.addEventListener('error', handle_error)

    return () => {
      window.removeEventListener('unhandledrejection', handle_rejection)
      window.removeEventListener('error', handle_error)
    }
  })
</script>
Carlocarload answered 7/4, 2023 at 18:16 Comment(0)
B
0

It's a limitation in the current implementation of the reactivity system (using a single scheduler). I've documented this and other shortcomings in: Svelte RFC 40

But there is good news on the horizon as Svelte v5 signal-based approach to reactivity doesn't seem to have this limitation.

Burchett answered 20/10, 2023 at 18:16 Comment(0)
R
-2

SvelteKit offers a hook called handleError, where you can handle errors both on client and server side.

References:

Rosemare answered 24/12, 2022 at 22:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.