diff --git a/packages/store/src/internal/unhandled-rxjs-error-callback.ts b/packages/store/src/internal/unhandled-rxjs-error-callback.ts index dc5bd189e..c671312ff 100644 --- a/packages/store/src/internal/unhandled-rxjs-error-callback.ts +++ b/packages/store/src/internal/unhandled-rxjs-error-callback.ts @@ -2,17 +2,19 @@ import { config } from 'rxjs'; const ɵɵunhandledRxjsErrorCallbacks = new WeakMap(); -const existingHandler = config.onUnhandledError; -config.onUnhandledError = function (error: any) { - const unhandledErrorCallback = ɵɵunhandledRxjsErrorCallbacks.get(error); - if (unhandledErrorCallback) { - unhandledErrorCallback(); - } else if (existingHandler) { - existingHandler.call(this, error); - } else { - throw error; - } -}; +export function setupOnUnhandhedErrorHandler(): void { + const existingHandler = config.onUnhandledError; + config.onUnhandledError = function (error: any) { + const unhandledErrorCallback = ɵɵunhandledRxjsErrorCallbacks.get(error); + if (unhandledErrorCallback) { + unhandledErrorCallback(); + } else if (existingHandler) { + existingHandler.call(this, error); + } else { + throw error; + } + }; +} export function executeUnhandledCallback(error: any) { const unhandledErrorCallback = ɵɵunhandledRxjsErrorCallbacks.get(error); diff --git a/packages/store/src/standalone-features/initializers.ts b/packages/store/src/standalone-features/initializers.ts index 406676e8c..282e45bf9 100644 --- a/packages/store/src/standalone-features/initializers.ts +++ b/packages/store/src/standalone-features/initializers.ts @@ -10,6 +10,7 @@ import { StatesAndDefaults } from '../internal/internals'; import { SelectFactory } from '../decorators/select/select-factory'; import { InternalStateOperations } from '../internal/state-operations'; import { LifecycleStateManager } from '../internal/lifecycle-state-manager'; +import { setupOnUnhandhedErrorHandler } from '../internal/unhandled-rxjs-error-callback'; /** * This function is shared by both NgModule and standalone features. @@ -17,6 +18,12 @@ import { LifecycleStateManager } from '../internal/lifecycle-state-manager'; * same initialization functionality. */ export function rootStoreInitializer(): void { + // Override the RxJS `config.onUnhandledError` within the root store initializer, + // but only after other code has already executed. + // If users have a custom `config.onUnhandledError`, we might overwrite it too + // early and capture the original `config.onUnhandledError` before it is properly set. + setupOnUnhandhedErrorHandler(); + const prebootFns = inject(NGXS_PREBOOT_FNS, { optional: true }) || []; prebootFns.forEach(prebootFn => prebootFn());