javascript / expert
Snippet
Enforcing Contextual Error Propagation via Custom Aggregate Wrappers in Store Subscriptions
When Svelte reactive subscriptions encounter unhandled exceptions within user callbacks, silent state corruption can occur. Utilizing JavaScript's native AggregateError preserves the original stack trace as a cause while augmenting error telemetry with contextual state diagnostics.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export function safeSubscribe(store, handler) {return store.subscribe((value) => {try {handler(value);} catch (cause) {const err = new AggregateError([cause],`Store subscriber failed for value: ${JSON.stringify(value)}`,{ cause });console.error(err);throw err;}});}
svelte
Breakdown
1
return store.subscribe((value) => {
Subscribes to Svelte store value emissions with an error-intercepting wrapper.
2
try { handler(value); } catch (cause) {
Executes the store subscriber logic inside a try-catch block to intercept thrown runtime exceptions.
3
const err = new AggregateError(
Instantiates an AggregateError containing the root failure along with contextual state info.
4
{ cause }
Attaches the original caught exception into the error's cause property for stack inspection.