javascript / expert
Snippet
Catching Unhandled Errors in Custom Svelte Store Subscriptions
Custom stores in Svelte follow the store contract by returning a subscribe function. When subscribers throw synchronous errors during notification, standard implementations crash the execution stack. Wrapping subscriber invocation in a try/catch block with a dedicated error handler ensures store resiliency during runtime exceptions.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export function createSafeStore(initialValue) {const subscribers = new Set();return {subscribe(subscriber, onError) {subscribers.add(subscriber);try {subscriber(initialValue);} catch (err) {if (onError) onError(err);else throw err;}return () => subscribers.delete(subscriber);}};}
svelte
Breakdown
1
export function createSafeStore(initialValue) {
Declares a factory function for instantiating a resilient custom store.
2
const subscribers = new Set();
Initializes a Set instance to track unique subscriber functions.
3
subscribe(subscriber, onError) {
Implements the Svelte store contract with an optional custom error callback parameter.
4
try { subscriber(initialValue); } catch (err) {
Executes the subscriber callback with the initial state while trapping thrown exceptions.
5
if (onError) onError(err); else throw err;
Delegates trapped errors to the provided handler or rethrows if unhandled.
6
return () => subscribers.delete(subscriber);
Returns an unsubscribe cleanup closure to remove the subscriber from the Set.