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>