The pipeline
Error isolation
Blex refuses to let a misbehaving observer break dispatch. Everything it swallows is handed to you instead.
The problem
A dispatch fans out to middleware, the DevTools bridge, persistence, history and every subscriber. If any one of them throws and the exception escapes, the observers registered after it never run - persistence silently stops saving because an unrelated analytics handler had a bad day. Blex isolates each of those call sites and routes the failure to a single sink.
builder.Services.AddBitBlexServices(options =>
{
options.OnError = error => logger.LogWarning(
error.Exception,
"[blex:{Source}] {Detail}",
error.Source,
error.Detail);
});
Without a handler, isolated errors are written to Console.Error - visible in the
browser console, but easy to miss. Setting OnError is the first thing to do in
any real app.
BlexError
public readonly record struct BlexError(
string Source,
Exception Exception,
string? Detail = null);
| Member | Description |
|---|---|
string Source |
Which part of the pipeline failed: subscriber, async reactor, middleware, persistence, restore, devtools, history, reset, register, unregister, dispose, prerender, dispatcher, mutation, query or startup - the table above says when each is raised. |
Exception Exception |
The captured exception. |
string? Detail |
Context - usually the store name, storage key or qualified action name. |
What gets reported
| Source | Raised when |
|---|---|
subscriber | A handler passed to Subscribe / SubscribeTo / SubscribeToAction threw. Detail is the qualified action name. |
async reactor | A SubscribeAsync handler's task faulted. |
middleware | A middleware's BeforeAction or OnAction threw. The pipeline continues with the next middleware. |
persistence | Rehydrating, unprotecting, applying, serializing, protecting, scheduling or writing a persisted slice failed - including the hydration of a store that registered after startup (its saves stay held until it hydrates) and the save a leaving store still owed. Detail names the store or key. |
restore | A store's slice could not be deserialized during RestoreGlobalState, or a StateRestored handler threw. A failing store is skipped; the others still restore. |
devtools | A time-travel snapshot from the extension was malformed, a sanitizer threw, the JS bridge failed to load or send, or an action typed into the dispatcher could not be dispatched - not JSON, no type, an unknown action, a missing argument, or an action that threw. |
history | A BlexHistory.Changed handler threw while recording or after an external restore, or a history filter, groupBy or scope predicate threw. |
reset | A store failed to reset during BlexManager.ResetAll(). That store is skipped; the rest still reset. |
register | Two stores were registered under the same name, so their state slices, DevTools entries and storage keys collide - or a StoreRegistered handler threw. |
unregister | A StoreUnregistered handler threw as a store left the manager. Detail names the store. |
dispose | Cancelling a store's in-flight effects threw while the store was disposed - a scope closing, or the container being torn down. The rest of the disposal carries on. Detail names the store. |
prerender | Handing a store's state - or the query cache - across the prerender-to-interactive boundary failed. The store simply renders from its own state instead, and a query fetches again - the worst case is rendering twice. |
dispatcher | A store changed outside the dispatcher its state belongs to (a timer, a background task, a SignalR handler). The change applied, but raced the renderer. Detail names the store. See Threads and the dispatcher. |
mutation | With DetectInPlaceMutations on: an action changed state without assigning a property. Detail is the qualified action name. |
query | A query observer's or mutation's handler threw, a mutation callback threw, or a handed-over query could not be read. Detail is the query key, when there is one. |
startup | Native .NET MAUI only: the startup initializer UseBitBlex() registers could not resolve the stores, the persistor or the history at MauiApp.Build() - typically scoped registrations under ValidateScopes. The app starts anyway; Detail says which registration to change. A failed hydration there is reported as persistence. See .NET MAUI. |
This registers a subscriber that throws on the next counter/Increment. The action still applies, the other observers still run, and the failure lands in the log below - and in the Inspector's Errors tab.
Note that Count still went up. The mutation had already been applied when the
subscriber ran - isolation protects the pipeline, it does not roll anything back.
Guarantees
- The mutation is recorded even if a subscriber throws. A standalone
Set XwhoseStateChangedhandler throws is still recorded, because the state genuinely changed - skipping the record would leave persistence, history and DevTools out of sync with reality. - Sanitizers fail closed. If your DevTools state sanitizer throws, Blex
sends an empty tree rather than the unsanitized one, so a bug in redaction
cannot leak the data it was meant to hide. A failing action sanitizer sends
<sanitizer-error>. - Corrupt persisted data never blocks startup. An unreadable payload is reported, discarded and removed from storage; the app starts with defaults.
- The handler itself is guarded. If your
OnErrorthrows, that exception is swallowed - it is the last line of defence, and there is nowhere left to report to.
A realistic handler
builder.Services.AddBitBlexServices(options =>
{
options.OnError = error =>
{
// Persistence and restore failures are worth alerting on; a broken
// analytics subscriber usually is not.
var level = error.Source is "persistence" or "restore"
? LogLevel.Error
: LogLevel.Warning;
logger.Log(level, error.Exception,
"Blex {Source} failed ({Detail})", error.Source, error.Detail);
};
});
BlexOptions is registered as a singleton, and the delegate you assign is
copied onto each scoped BlexManager as it is created. Do not close over a
scoped service in it - under Blazor Server that would capture one circuit's dependency
and share it with all of them. Close over something process-wide (an
ILoggerFactory, a metrics client), or assign
manager.OnError per scope instead.
Logging and tracing
options.UseLogging() does the handler above for you, through the host's
ILogger (category Bit.Blex): every action at Debug - or
the level you pass, LogLevel.None for failures only - every action failure as an
error, and every isolated failure as a warning, before your own OnError sees it too.
Names only: arguments and state never reach the log.
Tracing and metrics go through the standard ActivitySource and Meter
named BlexDiagnostics.SourceName, so OpenTelemetry, dotnet-counters and Application
Insights pick them up with no Blex-specific code - and with nothing listening, an action pays two
flag reads.
builder.Services.AddBitBlexServices(options => options.UseLogging());
builder.Services.AddOpenTelemetry()
.WithTracing(tracing => tracing.AddSource(BlexDiagnostics.SourceName))
.WithMetrics(metrics => metrics.AddMeter(BlexDiagnostics.SourceName));
What is recorded
| Member | Description |
|---|---|
Span "{store}/{action}" |
Every action and effect; one that runs inside another is its child. Tags blex.store, blex.action, blex.store.instance. Failed: status Error and error.type. Cancelled: blex.cancelled. An effect's retries are blex.effect.retry events. |
Span "query {resource}" |
Every query fetch, its retries included, with blex.query.outcome: success, error or cancelled. |
blex.actions / blex.action.errors |
Counters by blex.store and blex.action. |
blex.action.duration |
Histogram, in seconds - an async action's includes its awaits. |
blex.query.fetches / blex.query.duration |
By blex.query.resource and blex.query.outcome. |
Only names are recorded - never action arguments or state. A store's metric tag is its
declared name, without a scoped instance's key (which goes on the span only), so a thousand
open documents are one series. A query is named by its key's first part: ["todos", 42]
is "todos", so keep that part a fixed word rather than an id.
Setting it per scope
OnError is also a settable property on BlexManager, so a scoped
component or service can install its own handler where a scoped dependency is genuinely
needed.
[Inject] private BlexManager Manager { get; set; } = default!;
[Inject] private IToastService Toasts { get; set; } = default!; // scoped
protected override void OnInitialized()
=> Manager.OnError = error => Toasts.ShowWarning($"{error.Source}: {error.Exception.Message}");
This is about the observers of an action. An exception thrown by your own
[BlexAction] method body propagates to the caller as usual - only
[BlexEffect] bodies capture their exception, into the generated
XxxError property. Either way it reaches OnActionError,
and what the body changed before the throw stays changed unless the store is
RollbackOnError.