svelte: try block, like error boundary

Is your feature request related to a problem? Please describe.

I wonder would it possible to have a {#try} logic block, such that anything goes inside, if error would be handled in the {:catch} block, eg:

{#try}
   <Component />
{:catch}
   <div>Fallback uI </div>
{/try}

if an error thrown during init / update in <Component />, then will see the Fallback UI instead.

Describe the solution you’d like A clear and concise description of what you want to happen.

Describe alternatives you’ve considered A clear and concise description of any alternative solutions or features you’ve considered.

How important is this feature to you? Note: the more honest and specific you are here the more we will take you seriously.

Additional context Add any other context or screenshots about the feature request here.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 93
  • Comments: 17 (6 by maintainers)

Most upvoted comments

Good idea.

Maybe something like this would benefit even more, depending on the error getting thrown. So basically like a switch statement for catching errors.

<script>
import { GraphQLError } from 'graphql';
</script>


{#try}
   <Component />
{:catch GraphQLError}
	<div></div>
{:catch TypeError}
   <div></div>
{:catch}
   <div>Default fallback ui </div>
{/try}

Any updates due to Svelte5?

Yes, indeed, I’d like that. This is great. Simple and meers all requirements.

Component level is the right granularity. (If I want to catch something more specific, I can use try/catch.)

This could catch all the other error classes, like exceptions in $: statements, in markup {} code, in the initial execution of the JS section code, and many other error classes.

Errors in sub-components should bubble up and be caught by the onError() of the calling component. This would not force me to add an onError() in every single component. Bubbling would also allow to show errors in a custom UI for a specific bigger component, including errors in generic sub-components. The error UI would depend on the enclosing component, which is what we need for complex user-friendly apps.

@YamiOdymel, this feature request goes beyond simple error handling is more along the lines of React’s Error Boundaries.

Wouldn’t having a hook to deal with errors be better than handling errors in the markup? IMHO it’ll make it easy to manipulate the errors.

<script>
import { onError } from "svelte";
import { logger } from "analytics";

let error;

onError((_error) => {
    error = _error;
    logger.error(_error);
})
</script>

{#if error}
   <FallbackUI />
{:else}
   <Component />
{/if}