Open History to see the last commit
1---
2title: Error Handling
3id: error-handling
4---
5
6TanStack DB provides comprehensive error handling capabilities to ensure robust data synchronization and state management. This guide covers the built-in error handling mechanisms and how to work with them effectively.
7
8## Error Types
9
10TanStack DB provides named error classes for better error handling and type safety. All error classes can be imported from `@tanstack/db` (or more commonly, the framework-specific package e.g. `@tanstack/react-db`):
11
12```ts
13import {
14 SchemaValidationError,
15 CollectionInErrorStateError,
16 DuplicateKeyError,
17 MissingHandlerError,
18 TransactionError,
19 // ... and many more
20} from "@tanstack/db"
21```
22
23### SchemaValidationError
24
25Thrown when data doesn't match the collection's schema during insert or update operations:
26
27```ts
28import { SchemaValidationError } from "@tanstack/db"
29
30try {
31 todoCollection.insert({ text: 123 }) // Invalid type
32} catch (error) {
33 if (error instanceof SchemaValidationError) {
34 console.log(error.type) // 'insert' or 'update'
35 console.log(error.issues) // Array of validation issues
36 // Example issue: { message: "Expected string, received number", path: ["text"] }
37 }
38}
39```
40
41The error includes:
42- `type`: Whether it was an 'insert' or 'update' operation
43- `issues`: Array of validation issues with messages and paths
44- `message`: A formatted error message listing all issues
45
46**When schema validation occurs:**
47
48Schema validation happens only for **client mutations** - when you explicitly insert or update data:
49
501. **During inserts** - When `collection.insert()` is called
512. **During updates** - When `collection.update()` is called
52
53Schemas do **not** validate data coming from your server or sync layer. That data is assumed to already be valid.
54
55```typescript
56const schema = z.object({
57 id: z.string(),
58 created_at: z.string().transform(val => new Date(val))
59 // TInput: string, TOutput: Date
60})
61
62// Validation happens here ✓
63collection.insert({
64 id: "1",
65 created_at: "2024-01-01" // TInput: string
66})
67// If successful, stores: { created_at: Date } // TOutput: Date
68```
69
70For more details on schema validation and type transformations, see the [Schemas guide](./schemas.md).
71
72## Query Collection Error Tracking
73
74Query Collections report failures through the health tree, like every other
75Collection. A `queryFn` failure before the first successful result fails the
76first load: the status is `error`, and `preload()` rejects with the cause. Set
77`retry` so that a short outage is retried inside that first load. After the
78first result, a failed refetch sets the source node's `failureReason`, because
79TanStack Query fetches again. The rows stay, and the next successful result
80clears it:
81
82```tsx
83import { createCollection } from "@tanstack/db"
84import { queryCollectionOptions } from "@tanstack/query-db-collection"
85import { useLiveQuery } from "@tanstack/react-db"
86
87const syncedCollection = createCollection(
88 queryCollectionOptions({
89 queryClient,
90 queryKey: ["synced-data"],
91 queryFn: fetchData,
92 getKey: (item: Item) => item.id,
93 retry: 3,
94 })
95)
96
97function DataList() {
98 const { data, isSyncError } = useLiveQuery((q) =>
99 q.from({ item: syncedCollection })
100 )
101
102 return (
103 <>
104 {isSyncError && (
105 <Alert>
106 Unable to sync. Showing cached data.
107 <button
108 onClick={() => syncedCollection.utils.refetch({ throwOnError: true })}
109 >
110 Retry
111 </button>
112 </Alert>
113 )}
114 {/* Render data */}
115 </>
116 )
117}
118```
119
120`utils.refetch({ throwOnError: true })` retries and rejects when the retry
121fails. The `failureReason` stays visible while the retry is pending. During a
122mutation handler, the promise can resolve at the fetch boundary before the
123result applies and clears it.
124
125## Incremental Subset Load Errors
126
127An incremental `loadSubset` failure does not discard rows that are already
128available or put the shared source collection into `error`. A `loadSubset`
129that throws synchronously fails the same way as one that rejects: neither
130`requestSnapshot()` nor `setWindow()` throws, and the error arrives as a
131rejection. The failure belongs to the subscription that requested that
132subset:
133
134```ts
135const subscription = todoCollection.subscribeChanges(handleChanges, {
136 includeInitialState: false,
137})
138
139subscription.on('loadSubset:error', ({ error, options }) => {
140 console.error('Subset failed', options, error)
141})
142
143subscription.requestSnapshot()
144
145// The most recent failure remains available for diagnostics.
146console.log(subscription.lastError)
147```
148
149For ordered live queries, `utils.setWindow()` rejects with the same error. The
150last failure is also available as `utils.lastSubsetError`, while the last
151successful snapshot remains readable:
152
153```ts
154try {
155 await liveTodos.utils.setWindow({ offset: 0, limit: 100 })
156} catch (error) {
157 console.error(liveTodos.utils.lastSubsetError)
158}
159```
160
161Effects report subset failures through `onSourceError` and dispose because
162their incremental result can no longer be kept complete.
163
164A sync adapter's `unloadSubset` must not throw. If it does, TanStack DB reports
165the error as an uncaught error and continues as if the release had succeeded.
166The error is not a subset failure: it does not set `lastSubsetError`, reject
167`setWindow()`, dispose an Effect, or make `dispose()` or `cleanup()` reject.
168
169When a source change invalidates an ordered window, automatic full-source
170repair keeps the last complete snapshot visible. A failed repair exposes
171`utils.lastSubsetError` and retries at most twice, after 250 ms and 500 ms.
172Exhausting those retries does not put an already-ready query into a terminal
173error state or clear its rows. The app can show the error and explicitly retry
174with `setWindow()`. Cleanup or truncate cancels the old repair timer. Failed
175imperative window moves and initial loads do not use this background retry.
176
177For SQLite-persisted on-demand collections, a failed upstream `loadSubset`
178rejects even when hydration succeeded. Cached rows remain readable; their
179availability does not mean the remote request succeeded. Background coordinator
180retry, where supported, does not change the failed caller's outcome.
181
182When a must-refetch truncate cannot reload every active subset, a subscription
183keeps its last successful snapshot and reports the subset error. A live query
184shows it as an `error` on its own node until a later replay succeeds. It discards
185the incomplete replay batch and keeps later source changes private because they
186cannot prove a complete replacement. The next truncate retries every active
187subset. Overlapping truncates form one atomic replay: a newer truncate aborts
188the older attempt's requests, and an aborted request is over, so the replay
189does not wait for it. The newest attempt decides the result, and subscribers
190receive the replacement only when that attempt succeeds. Cleanup rejects window moves that
191are waiting for replay with `AbortError`.
192
193## Loading and Sync Errors
194
195An app that shows synced data asks two questions:
196
1971. **Can I show the data?** Read `status`.
1982. **Is the data on screen still being kept up to date?** Read `isSyncError` and `health`.
199
200TanStack DB answers them separately. Once a query has shown data, a network or
201backend failure never takes the data off the screen. It shows up in `health`,
202and the rows stay.
203
204```tsx
205import { eq, findProblems } from "@tanstack/db"
206import { useLiveQuery } from "@tanstack/react-db"
207
208function TaskList() {
209 const {
210 data,
211 isLoading,
212 isLoadingError,
213 isCrashed,
214 isSyncError,
215 health,
216 collection,
217 } = useLiveQuery((q) =>
218 q
219 .from({ task: taskCollection })
220 .join({ user: userCollection }, ({ task, user }) =>
221 eq(task.assigneeId, user.id)
222 )
223 )
224
225 if (isLoading) return <Spinner />
226 if (isLoadingError) return <LoadFailed onRetry={() => collection.reload()} />
227 if (isCrashed) return <StorageBroken />
228
229 return (
230 <>
231 {isSyncError && (
232 <SyncBanner health={health} onReload={() => collection.reload()} />
233 )}
234 {data.map((row) => (
235 <TaskRow key={row.task.id} {...row} />
236 ))}
237 </>
238 )
239}
240```
241
242### Status
243
244| `status` | Flag | Meaning | What the app does |
245| --- | --- | --- | --- |
246| `idle` | `isIdle` | Sync has not started. | Nothing yet. |
247| `loading` | `isLoading` | The first data is on its way. | Show a placeholder. |
248| `ready` | `isReady` | The data can be shown. | Show it. Check `isSyncError` for a banner. |
249| `error` | `isLoadingError` | The first load failed. There is nothing to show. | Show a failure screen and offer `reload()`. |
250| `crashed` | `isCrashed` | Local storage broke. Nothing recovers it in place. | Clean it up with its dependents and start it again (see [When a Collection crashes](#when-a-collection-crashes)). |
251| `cleaned-up` | `isCleanedUp` | The Collection was cleaned up. | Nothing. |
252
253Two rules make `status` predictable:
254
255- **After a query has shown data, only a crash changes its status.** A dropped
256 connection, a failed refetch, or a backend that stops answering appears in
257 `health`. `isLoadingError` therefore always means "nothing to show yet".
258- **A query takes the worst status of its sources until it is ready.** If any
259 source fails its first load, the query's status is `error`, and `preload()`
260 rejects with the cause.
261
262`isError` is removed. Use `isLoadingError` and `isCrashed`, which need
263different handling.
264
265### Sync errors: the `health` tree
266
267`health` has one node for the query itself and one for each source in the
268query, in query order. The tree's shape is fixed by the query, so you can
269render, log, or send it to monitoring. A disabled query has no query
270definition, so its `health` is `undefined`.
271
272```ts nocheck
273{
274 alias: "root", kind: "live-query", status: "ready", hasErrors: true,
275 failureReason: null, error: null, reloading: false,
276 sources: [
277 { alias: "task", kind: "source", status: "ready", hasErrors: false,
278 failureReason: null, error: null, reloading: false, sources: [] },
279 { alias: "user", kind: "source", status: "ready", hasErrors: true,
280 failureReason: { name: "FetchError", message: "Network request failed", at: 1760342400000,
281 errors: [{ name: "FetchError", message: "Network request failed", at: 1760342400000 }] },
282 error: null, reloading: false, sources: [] },
283 ],
284}
285```
286
287A node can show one of two problems. They follow TanStack Query's
288`failureReason` and `error`:
289
290| Field | Meaning | What the app does |
291| --- | --- | --- |
292| `failureReason` | Something went wrong, and the sync adapter is still trying. It clears by itself when sync works again. | Show "Reconnecting…" or nothing. Wait. |
293| `error` | The sync adapter stopped, or the first load failed. The rows from this source stay but no longer update. | Show "Updates stopped" and offer `reload()`. |
294
295`isSyncError` is `true` when the query is `ready` and any node has a
296`failureReason` or an `error`. `hasErrors` on a node says whether that node or
297any node below it has one.
298
299Each problem is `{ name, message, code?, at, cause, errors }`. `cause` holds
300the exact value the adapter reported, for example the `Response` or the error
301your `queryFn` threw. Every other field is plain JSON. The problem's own fields
302are its newest failure; `errors` lists every failure of the problem, oldest
303first (see [Every failure of a problem](#every-failure-of-a-problem)). A node keeps its object
304identity until something in its part of the tree changes, so `===` and
305`useMemo` work on it. Server-side rendering does not transfer `health`; the
306client builds its own tree from its own sync.
307
308`failureReason` says that the adapter is trying, not that trying will help. An
309expired token gives a `failureReason` on every refetch until the user signs in.
310Use `code` or `cause` for cases like this:
311
312```tsx
313import { findProblems, type HealthNode } from "@tanstack/db"
314
315function SyncBanner({
316 health,
317 onReload,
318}: {
319 health: HealthNode
320 onReload: () => void
321}) {
322 const [first] = findProblems(health) // nodes with a problem, in query order
323 if (first?.failureReason?.code === "401") return <SignInAgain />
324 if (first?.error) return <UpdatesStopped onReload={onReload} />
325 return <Reconnecting />
326}
327```
328
329`findProblems(health)` walks the tree and returns every node that has a
330problem of its own, in query order. Use it for the message on a failure screen
331too: when `isLoadingError` is true, the first node it returns holds the first
332load failure in its `error`.
333
334A Collection used twice in one query, for example in a self-join, has one node
335per alias. An include has one node, which shows the include's source; its
336per-row child Collections are not in the tree. A nested live query's node
337carries its own sources.
338
339#### Every failure of a problem
340
341A problem can have more than one failure. Its `message`, `cause`, and `at` are
342the newest failure's, so code that reads only those keeps working. `errors`
343lists each failure, oldest first, as `{ name, message, code?, at, cause }`:
344
345- A source's `failureReason` lists each `reportError()` of the sync run since
346 it began, for example each failed refetch of a query Collection. One error
347 value is one failure: a value that is already listed keeps its place and
348 its `at`. `reportHealthy(error)` removes that value's failure, for example
349 when one of several failing queries recovers, and the other failures stay.
350 `reportHealthy()` ends the list, and a `reload()` whose new sync run reports
351 starts a new list.
352- An `error` from `fail()`, a failed first load, or a crash has one failure.
353- A query's own `error` lists every failed request for more data that is still
354 failing. A request that loads, or that the query no longer needs, leaves the
355 list. Two requests that fail with the same error are one entry. When a
356 source's reload cannot load the query's data again, the list has every load
357 that failed.
358
359Adding or removing a failure is a change: the node is a new object and
360`health:change` fires.
361
362```tsx
363function RetryLog({ health }: { health: HealthNode }) {
364 const problem = health.sources[0]?.failureReason
365 if (!problem) return null
366 return (
367 <details>
368 <summary>
369 Reconnecting: {problem.message} ({problem.errors.length} failures)
370 </summary>
371 <ul>
372 {problem.errors.map((failure, index) => (
373 <li key={index}>{failure.message}</li>
374 ))}
375 </ul>
376 </details>
377 )
378}
379```
380
381### Collections without a live query
382
383Every Collection has the same surface, so code that uses a Collection directly
384does not need a live query:
385
386```ts
387todos.status // 'loading' | 'ready' | 'error' | 'crashed' | ...
388todos.health // one node: { status, failureReason, error, reloading, ... }
389todos.on("health:change", ({ collection }) => report(collection.health))
390await todos.reload()
391```
392
393A live query is a Collection too; its `health` is the whole tree.
394
395### Failed requests for more data
396
397After a query is ready it can ask for more data: the next page of an infinite
398query, or rows for a newly joined key. When that request fails, the query's own
399node (`root`) shows an `error`. The sources stay healthy and the rows already
400shown stay. The error clears when the data loads, or when the query no longer
401needs it, for example after the user scrolls back. When several requests fail,
402the node shows the newest, and its `errors` lists every request still failing.
403A request that TanStack DB cancels, for example because the window moved on,
404is over: its late result changes nothing. When a source's reload or truncate
405loads the query's data again, that replay decides the query's failed
406requests: its success clears them all, and its failure replaces them with
407the replay's own failures.
408
409```tsx
410const { data, health, fetchNextPage } = useLiveInfiniteQuery(
411 (q) =>
412 q
413 .from({ post: postCollection })
414 .orderBy(({ post }) => post.createdAt, "desc"),
415 { pageSize: 20 }
416)
417
418{
419 health?.error && (
420 <button onClick={() => fetchNextPage()}>Retry loading more</button>
421 )
422}
423```
424
425### Reloading
426
427`collection.reload()` starts a new sync run for a Collection. Nothing
428visible changes until the reload completes.
429
430- The current rows, `status`, and any `error` stay on screen. The node shows
431 `reloading: true`.
432- The new run's writes apply on the rows the Collection keeps. The new run
433 replaces every row only with a snapshot, a transaction its sync adapter
434 begins with `begin({ snapshot: true })`, or with the adapter's own
435 `truncate()`. Then the new rows replace the old rows in one change.
436- The reload completes when that replacement applies, or when the new run
437 calls `markReady()`. A reload without a snapshot keeps the rows. At
438 completion the node drops the old run's problems. A Collection in `error`
439 becomes `ready` when the new run calls `markReady()`.
440- If the new run fails, the old rows and status stay, the node shows the new
441 `error`, and the `reload()` promise rejects.
442- A reload keeps every row its new run does not rewrite. Core never deletes
443 rows on its own after a reload: a row the backend deleted goes when the
444 sync adapter sends a snapshot, a `delete`, or its own cleanup of that
445 row ([#2269](https://github.com/TanStack/db/issues/2269)).
446- A live query's own reload keeps its rows and its window (the offset and
447 limit it settled on) until its new run has a complete result, then shows
448 that result in one change.
449- During a reload, `health` shows the new run's own problems as they happen:
450 a failure it reports shows at once, and its recovery clears the old
451 failure reason.
452
453On a live query, `reload()` reloads each of its sources that has an `error`,
454then the query itself if its own node has an `error`: its first load failed,
455or a request for more data failed. To reload one source instead, call
456`reload()` on that source's Collection; a query in `error` stays there until
457its own `reload()`. A source's reload also loads the query's data again, so it
458clears all of the query's failed requests when that replay succeeds.
459
460```ts
461// Retry a failed first load every 30 seconds until the backend is back.
462useEffect(() => {
463 if (!isLoadingError) return
464 const id = setInterval(() => collection.reload().catch(() => {}), 30_000)
465 return () => clearInterval(id)
466}, [isLoadingError, collection])
467```
468
469Calling `reload()` while a reload is in flight returns the same promise. On a
470`crashed` Collection it rejects with `CollectionReloadCrashedError`.
471
472Use `reload()` for retries the user or the app decides on. Retries inside one
473attempt belong to the sync adapter: for example, set `retry` on a Query
474Collection, so a short outage never reaches `isLoadingError`.
475
476### When a Collection crashes
477
478A Collection crashes when its local storage can no longer serve reads or
479accept writes:
480
481- its IndexedDB connection closed (for example after a `versionchange` from
482 another tab);
483- a local SQLite persistence write or restore failed;
484- its sync function threw, or an internal invariant failed.
485
486The Collection moves to `crashed`, and so does every live query and Effect over
487it, even after they were ready. A crash cannot be recovered in place: nothing
488restarts it, and `reload()` rejects. To recover, clean up the Collection
489together with everything that reads from it. Cleanup discards all of its state,
490so the next `preload()` or subscriber starts it fresh, as a new Collection
491would. If the cause remains, for example a bug in the sync function, the fresh
492start crashes again.
493
494```ts
495console.log(todos.subscribers) // live queries, Effects, and raw subscriptions
496await todos.cleanup({ dependents: true })
497await todos.preload() // a fresh start; mount the queries again
498```
499
500### Cleaning up a Collection
501
502`cleanup()` rejects with `CollectionHasSubscribersError` while a live query
503with subscribers or an Effect still reads the Collection, because those readers
504would lose their data. Unmount the components that read it first, or pass
505`{ dependents: true }` to end its live queries and Effects first. Raw
506`subscribeChanges()` subscriptions do not block cleanup and are not ended by
507it. `collection.subscribers` lists every dependent with its `kind`. Collections
508that nothing reads are cleaned up automatically after `gcTime`.
509
510### Persisted Collections
511
512A persisted Collection restores its rows from local storage before the remote
513syncs. By default it becomes `ready` only through its sync adapter. With
514`initialRender: { strategy: "network-first", networkTimeoutMs }`, restored rows
515make it `ready` once the deadline passes or the remote fails its first load. An
516empty restore keeps it `loading`, and a failed restore crashes it. See
517[Render after SQLite restore](./sqlite-persistence.md#render-after-sqlite-restore).
518
519Only a local storage failure crashes a persisted Collection. A remote subset
520request that the persistence layer makes for the sync adapter can also fail:
521acquiring, releasing, refreshing, or reacquiring a subset through the
522coordinator. The source keeps syncing, so on a `ready` Collection the failure
523shows as `health.failureReason`, and the status and rows do not change. The next remote request that succeeds clears those failures. Before
524the first ready it is only logged, and a load that waited on the request
525rejects with its error. An `unloadSubset` that throws or rejects is reported
526uncaught, as it is without persistence. After `reload()`, a late failure of
527the retired sync run's requests does not reach the new run.
528
529### Effects
530
531An Effect ends when a source it reads fails its first load or crashes, or when
532a load it needs fails; it calls `onSourceError(error)`. After its initial
533load, a sync problem on a source calls `onHealthChange(health)` with the same
534tree a live query returns, and the Effect keeps running.
535
536```ts
537createEffect({
538 query: (q) => q.from({ order: orders }),
539 onBatch: (events) => {
540 /* ... */
541 },
542 onHealthChange: (health) => {
543 if (health.hasErrors) pauseAutomations()
544 else resumeAutomations()
545 },
546})
547```
548
549### Using Suspense and Error Boundaries (React)
550
551`useLiveSuspenseQuery` suspends while `loading` and throws an Error to the
552nearest error boundary for `error`. The Error is the first load's cause when
553that cause is an Error. Otherwise it is an Error with the problem's message
554(`health.error.message`) whose `cause` holds the value the sync adapter
555reported. It throws for `crashed` at any time, by the same rule. Sync problems
556after the first data never reach the boundary; read `health` from the hook, as
557in TanStack Query.
558
559```tsx
560import { useLiveSuspenseQuery } from "@tanstack/react-db"
561import { Suspense } from "react"
562import { ErrorBoundary } from "react-error-boundary"
563
564const TodoList = () => {
565 const { data, health } = useLiveSuspenseQuery((query) =>
566 query.from({ todos: todoCollection })
567 )
568
569 // data is always defined here, so any problem in the tree is a sync problem
570 return (
571 <>
572 {health?.hasErrors && <div>Todos may be out of date.</div>}
573 {data.map((todo) => (
574 <div key={todo.id}>{todo.text}</div>
575 ))}
576 </>
577 )
578}
579
580const App = () => (
581 <ErrorBoundary fallback={<div>Failed to load todos</div>}>
582 <Suspense fallback={<div>Loading...</div>}>
583 <TodoList />
584 </Suspense>
585 </ErrorBoundary>
586)
587```
588
589See the [React Suspense section in Live Queries](./live-queries#using-with-react-suspense) for more details.
590
591### For sync adapter authors
592
593A sync adapter reports failures with three calls:
594
595| Call | Meaning | Effect |
596| --- | --- | --- |
597| `reportError(error)` | Something went wrong; I am still trying. | Sets `failureReason` and adds the failure to its `errors`. An `error` value that is already listed changes nothing. Only after the first ready. |
598| `fail(error)` | I stopped. | Before the first ready: `status: 'error'`. After: the node's `error`; the rows stay. |
599| `reportHealthy()` | Sync works again. | Clears `failureReason`. Only after the first ready. |
600| `reportHealthy(error)` | This part works again. | Removes the failure whose cause is `error` from `errors`. `failureReason` clears when no failure is left. Only after the first ready. |
601
602```ts
603sync: ({ begin, write, commit, markReady, reportError, fail, reportHealthy }) => {
604 let ready = false
605 const stream = connect({
606 onData: (changes) => {
607 // The run's first batch is all of its rows: a snapshot replaces
608 // the rows that a reload keeps. Each later batch carries the
609 // stream's own change types, so a held row gets an update.
610 begin(ready ? undefined : { snapshot: true })
611 changes.forEach(({ type, value }) => write({ type, value }))
612 commit()
613 if (ready) reportHealthy()
614 else markReady()
615 ready = true
616 },
617 onError: (error, { willRetry }) => {
618 if (!willRetry) fail(error)
619 else if (ready) reportError(error)
620 },
621 })
622 return () => stream.close()
623}
624```
625
626- Retry inside the first load before calling `fail`. While you retry before
627 the first ready, call nothing; the Collection stays `loading`.
628- These calls follow the Collection's state machine, and a call that does not
629 fit it throws: `reportError` or `reportHealthy` before the first ready, or
630 after `fail`. `markReady` after the run is ready, or after its `fail`, does
631 nothing. Calls after a crash do nothing. `reportHealthy` when nothing is wrong changes
632 nothing, so you can call it after every commit.
633- When several parts of your source can fail at the same time, such as
634 separate requests, report each part's own error and call
635 `reportHealthy(error)` with that error when the part recovers. The other
636 failures stay listed. `reportHealthy(error)` for an error that is not
637 listed changes nothing.
638- An `error` from `fail` clears only through `reload()`, which calls your
639 `sync` function again for a new run.
640- Keep the run's readiness in your `sync` function, as `ready` above does.
641 Do not read `collection.status` to learn whether this run is ready: during
642 a reload it still shows the previous run's status.
643- During a reload, your `sync` function runs again while the Collection still
644 holds the previous run's rows. Send the new run's full state as one
645 snapshot (`begin({ snapshot: true })`), or write against the kept rows:
646 `update` a row the Collection holds, `delete` a row that is gone, then call
647 `markReady()`. Your adapter has four obligations during a reload
648 ([#2269](https://github.com/TanStack/db/issues/2269)):
649 - Never `insert` a key the Collection holds: write `update` for it. An
650 `insert` of a held key with a different value throws
651 `DuplicateKeySyncError`, during a reload as at any time, also for a
652 replayed `loadSubset` that lands after the reload completed.
653 - Remove the rows the backend deleted yourself. Core does not delete kept
654 rows after a reload. An on-demand Collection's `loadSubset` result is
655 partial, so never mark it as a snapshot; delete a row from your stream,
656 or through the row ownership your adapter keeps.
657 - Honor the `loadSubset` signal. When it aborts, the load is over for
658 core: stop the fetch and write no rows for it. Core ignores a later
659 resolve or reject of that load.
660 - A `loadSubset` that throws synchronously fails the load exactly as one
661 that returns a rejected promise.
662
663### Migrating
664
665If you're upgrading from 0.9.2 to the 1.0 RC, update your error handling as
666shown below. For the other breaking changes, see
667[Migrating to the 1.0 RC](./migrate-to-1-0-rc.md).
668
669| Before | After |
670| --- | --- |
671| `isError` | `isLoadingError` (first load failed) or `isCrashed` (storage broke) |
672| `status: 'error'` after a crash | `status: 'crashed'` |
673| `markError(error)` | `fail(error)` |
674| `cleanup()` then `preload()` to recover | `reload()` |
675| `cleanup()` with live queries mounted | rejects; unmount first or `cleanup({ dependents: true })` |
676| query-db `utils.lastError`, `isError`, `errorCount`, `clearError()` | `health`, `reload()` |
677
678## Transaction Error Handling
679
680When mutations fail, TanStack DB automatically rolls back optimistic updates:
681
682```ts
683const todoCollection = createCollection(
684 queryCollectionOptions<{ id: string; text: string; completed: boolean }>({
685 queryKey: ["todos"],
686 queryClient,
687 queryFn: fetchTodos,
688 getKey: (todo) => todo.id,
689 id: "todos",
690 onInsert: async ({ transaction, collection }) => {
691 const response = await fetch("/api/todos", {
692 method: "POST",
693 body: JSON.stringify(transaction.mutations[0].modified),
694 })
696 if (!response.ok) {
697 // Throwing an error will rollback the optimistic state
698 throw new Error(`HTTP Error: ${response.status}`)
699 }
700
701 await collection.utils.refetch()
702 },
703}))
704
705// Usage - optimistic update will be rolled back if the mutation fails
706try {
707 const tx = todoCollection.insert({
708 id: "1",
709 text: "New todo",
710 completed: false,
711 })
713 await tx.when('settled')
714} catch (error) {
715 // The optimistic update has been automatically rolled back
716 console.error("Failed to create todo:", error)
717}
718```
719
720### Transaction States and Error Information
721
722Transactions have the following states:
723- `pending` - Transaction is being processed
724- `persisting` - Currently executing the mutation function
725- `completed` - Transaction completed successfully
726- `failed` - Transaction failed and was rolled back
727
728Access transaction error information from collection operations:
729
730```ts
731const todoCollection = createCollection({
732 id: "todos",
733 onUpdate: async ({ transaction }) => {
734 const response = await fetch(`/api/todos/${transaction.mutations[0].key}`, {
735 method: "PUT",
736 body: JSON.stringify(transaction.mutations[0].modified),
737 })
739 if (!response.ok) {
740 throw new Error(`Update failed: ${response.status}`)
741 }
742 },
743})
744
745try {
746 const tx = await todoCollection.update("todo-1", (draft) => {
747 draft.completed = true
748 })
750 await tx.when('settled')
751} catch (error) {
752 // Transaction has been rolled back
753 console.log(tx.state) // "failed"
754 console.log(tx.error) // { message: "Update failed: 500", error: Error }
755}
756```
757
758Or with manual transaction creation:
759
760```ts
761const tx = createTransaction({
762 mutationFn: async ({ transaction }) => {
763 throw new Error("API failed")
764 }
765})
766
767tx.mutate(() => {
768 collection.insert({ id: "1", text: "Item" })
769})
770
771try {
772 await tx.commit()
773} catch (error) {
774 // Transaction has been rolled back
775 console.log(tx.state) // "failed"
776 console.log(tx.error) // { message: "API failed", error: Error }
777}
778```
779
780Explicit cancellation is different from a mutation failure. If you call
781`tx.rollback()` while `mutationFn` is pending, the rollback settles
782`tx.when('settled')` as rejected. A later result or rejection from that
783mutation function is ignored: the outstanding `commit()` call resolves and
784`tx.error` is not populated by that late rejection. Observe `tx.when('settled')`
785when you need the transaction's outcome, including explicit cancellation.
786
787After the mutation function succeeds, a publication listener can still throw
788while the completed transaction updates its collections. In that case
789`commit()` rejects with the listener error, but `tx.when('settled')` resolves
790and the transaction remains completed. This is not a persistence failure.
791
792## Collection Operation Errors
793
794### Invalid Collection State
795
796A Collection whose first load failed (status `error`) or that crashed (status
797`crashed`) rejects writes with `CollectionInErrorStateError`. Recover by
798status:
799
800- `error`: call `reload()`. It starts a new sync run, and live queries over the
801 Collection follow it. See [Reloading](#reloading).
802- `crashed`: a crash cannot be recovered in place, and `reload()` rejects.
803 Clean up the Collection together with everything that reads from it, then
804 start it again. Plain `cleanup()` rejects with `CollectionHasSubscribersError`
805 while a live query or an Effect reads the Collection. See
806 [When a Collection crashes](#when-a-collection-crashes).
807
808```ts
809import { CollectionInErrorStateError } from "@tanstack/db"
810
811try {
812 todoCollection.insert(newTodo)
813} catch (error) {
814 if (error instanceof CollectionInErrorStateError) {
815 if (todoCollection.status === "crashed") {
816 // Ends its live queries and Effects first; mount them again afterward.
817 await todoCollection.cleanup({ dependents: true })
818 await todoCollection.preload() // a fresh start
819 } else {
820 await todoCollection.reload() // the first load failed: try again
821 }
822
823 // Now retry the operation
824 todoCollection.insert(newTodo)
825 }
826}
827```
828
829### Missing Mutation Handlers
830
831Direct mutations require handlers to be configured:
832
833```ts
834const todoCollection = createCollection({
835 id: "todos",
836 getKey: (todo) => todo.id,
837 // Missing onInsert handler
838})
839
840// This will throw an error
841todoCollection.insert(newTodo)
842// Error: Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured
843```
844
845### Insert Operation Errors
846
847#### DuplicateKeyError
848
849Thrown when inserting items with existing keys:
850
851```ts
852import { DuplicateKeyError } from "@tanstack/db"
853
854try {
855 todoCollection.insert({ id: "existing-id", text: "Todo" })
856} catch (error) {
857 if (error instanceof DuplicateKeyError) {
858 console.log(`Duplicate key: ${error.message}`)
859 // Consider using update() instead, or check if item exists first
860 }
861}
862```
863
864#### UndefinedKeyError
865
866Thrown when an object is created without a defined key:
867
868```ts
869import { UndefinedKeyError } from "@tanstack/db"
870
871const collection = createCollection({
872 id: "todos",
873 getKey: (item) => item.id,
874})
875
876try {
877 collection.insert({ text: "Todo" }) // Missing 'id' field
878} catch (error) {
879 if (error instanceof UndefinedKeyError) {
880 console.log("Item is missing required key field")
881 // Ensure your items have the key field defined by getKey
882 }
883}
884```
885
886### Update Operation Errors
887
888#### UpdateKeyNotFoundError
889
890Thrown when trying to update a key that doesn't exist in the collection:
891
892```ts
893import { UpdateKeyNotFoundError } from "@tanstack/db"
894
895try {
896 todoCollection.update("nonexistent-key", draft => {
897 draft.completed = true
898 })
899} catch (error) {
900 if (error instanceof UpdateKeyNotFoundError) {
901 console.log("Key not found - item may have been deleted")
902 // Consider using insert() if the item doesn't exist
903 }
904}
905```
906
907#### KeyUpdateNotAllowedError
908
909Thrown when attempting to change an item's key (not allowed - delete and re-insert instead):
910
911```ts
912import { KeyUpdateNotAllowedError } from "@tanstack/db"
913
914try {
915 todoCollection.update("todo-1", draft => {
916 draft.id = "todo-2" // Not allowed!
917 })
918} catch (error) {
919 if (error instanceof KeyUpdateNotAllowedError) {
920 console.log("Cannot change item keys")
921 // Instead, delete the old item and insert a new one
922 }
923}
924```
925
926### Delete Operation Errors
927
928#### DeleteKeyNotFoundError
929
930Thrown when trying to delete a key that doesn't exist:
931
932```ts
933import { DeleteKeyNotFoundError } from "@tanstack/db"
934
935try {
936 todoCollection.delete("nonexistent-key")
937} catch (error) {
938 if (error instanceof DeleteKeyNotFoundError) {
939 console.log("Key not found - item may have already been deleted")
940 // This may be acceptable in some scenarios (idempotent deletes)
941 }
942}
943```
944
945## Sync Error Handling
946
947### Query Collection Sync Errors
948
949Query collections distinguish an initial load failure from a later refetch failure:
950
951```ts
952import { createCollection } from "@tanstack/db"
953import { queryCollectionOptions } from "@tanstack/query-db-collection"
954
955const todoCollection = createCollection(
956 queryCollectionOptions<{ id: string; text: string; completed: boolean }>({
957 queryKey: ["todos"],
958 queryFn: async () => {
959 const response = await fetch("/api/todos")
960 if (!response.ok) {
961 throw new Error(`Failed to fetch: ${response.status}`)
962 }
963 return response.json()
964 },
965 queryClient,
966 getKey: (item) => item.id,
967 schema: todoSchema,
968 // Standard TanStack Query error handling options
969 retry: 3,
970 retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
971 })
972)
973```
974
975When sync errors occur:
976- Error is logged to console: `[QueryCollection] Error observing query...`
977- A failure before the first successful result fails the first load: the status is `error`, and readiness waits such as `preload()` and `toArrayWhenReady()` reject with the cause
978- A later refetch failure keeps the Collection `ready` with its cached data and sets the source node's `failureReason`, because TanStack Query fetches again
979- A later successful refetch clears the `failureReason`
980- To retry a failed first load, call `collection.reload()`
981
982### Sync Write Errors
983
984Sync functions must handle their own errors during write operations:
985
986```ts
987const collection = createCollection({
988 id: "todos",
989 sync: {
990 sync: ({ begin, write, commit }) => {
991 begin()
993 try {
994 // Will throw if key already exists
995 write({ type: "insert", value: { id: "existing-id", text: "Todo" } })
996 } catch (error) {
997 // Error: Cannot insert document with key "existing-id" from sync because it already exists
998 }
1000 commit()
1001 }
1002 }
1003})
1004```
1005
1006### Cleanup Error Handling
1007
1008Cleanup errors are isolated to prevent blocking the cleanup process:
1009
1010```ts
1011const collection = createCollection({
1012 id: "todos",
1013 sync: {
1014 sync: ({ begin, commit }) => {
1015 begin()
1016 commit()
1018 // Return a cleanup function
1019 return () => {
1020 // If this throws, the error is re-thrown in a microtask
1021 // but cleanup continues successfully
1022 throw new Error("Sync cleanup failed")
1023 }
1024 },
1025 },
1026})
1027
1028// Cleanup completes even if the sync cleanup function throws
1029await collection.cleanup() // Resolves successfully
1030// Error is re-thrown asynchronously via queueMicrotask
1031```
1032
1033## Error Recovery Patterns
1034
1035### Reload or Recreate
1036
1037To retry a failed first load or a stopped sync, call `reload()` on the
1038Collection or on the live query that reads it. See [Reloading](#reloading). A
1039crashed Collection cannot reload; clean it up with `{ dependents: true }` and
1040start it again. See [When a Collection crashes](#when-a-collection-crashes).
1041
1042### Graceful Degradation
1043
1044After the first ready, Collections keep working with their rows when sync
1045fails. The health tree tells you which source has the problem and whether its
1046sync adapter is still trying:
1047
1048```tsx
1049import { findProblems } from "@tanstack/db"
1050import { useLiveQuery } from "@tanstack/react-db"
1051
1052const TodoApp = () => {
1053 const { data, health, collection } = useLiveQuery((query) =>
1054 query.from({ todos: todoCollection })
1055 )
1056 const [problem] = health ? findProblems(health) : []
1057
1058 return (
1059 <div>
1060 {problem?.error && (
1061 <div>
1062 Sync stopped.{" "}
1063 <button onClick={() => collection.reload()}>Reload</button>
1064 </div>
1065 )}
1066 {problem?.failureReason && <div>Reconnecting. Showing saved data.</div>}
1067 {data.map((todo) => <TodoItem key={todo.id} todo={todo} />)}
1068 </div>
1069 )
1070}
1071```
1072
1073### Transaction Rollback Cascading
1074
1075When a transaction fails, conflicting transactions are automatically rolled back:
1076
1077```ts
1078const tx1 = createTransaction({ mutationFn: async () => {} })
1079const tx2 = createTransaction({ mutationFn: async () => {} })
1080
1081tx1.mutate(() => collection.update("1", draft => { draft.value = "A" }))
1082tx2.mutate(() => collection.update("1", draft => { draft.value = "B" })) // Same item
1083
1084// Rolling back tx1 will also rollback tx2 due to conflict
1085tx1.rollback() // tx2 is automatically rolled back
1086```
1087
1088### Transaction Lifecycle Errors
1089
1090Transactions validate their state before operations to prevent misuse. Here are the specific errors you may encounter:
1091
1092#### MissingMutationFunctionError
1093
1094Thrown when creating a transaction without a required `mutationFn`:
1095
1096```ts
1097import { MissingMutationFunctionError } from "@tanstack/db"
1098
1099try {
1100 const tx = createTransaction({}) // Missing mutationFn
1101} catch (error) {
1102 if (error instanceof MissingMutationFunctionError) {
1103 console.log("mutationFn is required when creating a transaction")
1104 }
1105}
1106```
1107
1108#### TransactionNotPendingMutateError
1109
1110Thrown when calling `mutate()` after a transaction is no longer pending:
1111
1112```ts
1113import { TransactionNotPendingMutateError } from "@tanstack/db"
1114
1115const tx = createTransaction({ mutationFn: async () => {} })
1116
1117await tx.commit()
1118
1119try {
1120 tx.mutate(() => {
1121 collection.insert({ id: "1", text: "Item" })
1122 })
1123} catch (error) {
1124 if (error instanceof TransactionNotPendingMutateError) {
1125 console.log("Cannot mutate - transaction is no longer pending")
1126 }
1127}
1128```
1129
1130#### TransactionNotPendingCommitError
1131
1132Thrown when calling `commit()` after a transaction is no longer pending:
1133
1134```ts
1135import { TransactionNotPendingCommitError } from "@tanstack/db"
1136
1137const tx = createTransaction({ mutationFn: async () => {} })
1138tx.mutate(() => collection.insert({ id: "1", text: "Item" }))
1139
1140await tx.commit()
1141
1142try {
1143 await tx.commit() // Trying to commit again
1144} catch (error) {
1145 if (error instanceof TransactionNotPendingCommitError) {
1146 console.log("Transaction already committed")
1147 }
1148}
1149```
1150
1151#### TransactionAlreadyCompletedRollbackError
1152
1153Thrown when calling `rollback()` on a transaction that's already completed:
1154
1155```ts
1156import { TransactionAlreadyCompletedRollbackError } from "@tanstack/db"
1157
1158const tx = createTransaction({ mutationFn: async () => {} })
1159tx.mutate(() => collection.insert({ id: "1", text: "Item" }))
1160
1161await tx.commit()
1162
1163try {
1164 tx.rollback() // Can't rollback after commit
1165} catch (error) {
1166 if (error instanceof TransactionAlreadyCompletedRollbackError) {
1167 console.log("Cannot rollback - transaction already completed")
1168 }
1169}
1170```
1171
1172### Sync Transaction Errors
1173
1174When working with sync transactions, these errors can occur:
1175
1176#### NoPendingSyncTransactionWriteError
1177
1178Thrown when calling `write()` without an active sync transaction:
1179
1180```ts
1181const collection = createCollection({
1182 id: "todos",
1183 sync: {
1184 sync: ({ write }) => {
1185 // Calling write without begin() first
1186 write({ type: "insert", value: { id: "1", text: "Todo" } })
1187 // Error: No pending sync transaction to write to
1188 }
1189 }
1190})
1191```
1192
1193#### SyncTransactionAlreadyCommittedWriteError
1194
1195Thrown when calling `write()` after the sync transaction is already committed:
1196
1197```ts
1198const collection = createCollection({
1199 id: "todos",
1200 sync: {
1201 sync: ({ begin, write, commit }) => {
1202 begin()
1203 commit()
1204
1205 // Trying to write after commit
1206 write({ type: "insert", value: { id: "1", text: "Todo" } })
1207 // Error: The pending sync transaction is already committed
1208 }
1209 }
1210})
1211```
1212
1213#### NoPendingSyncTransactionCommitError
1214
1215Thrown when calling `commit()` without an active sync transaction.
1216
1217#### SyncTransactionAlreadyCommittedError
1218
1219Thrown when calling `commit()` on a sync transaction that's already committed.
1220
1221## Best Practices
1222
12231. **Use instanceof checks** - Use `instanceof` instead of string matching for error handling:
1224 ```ts
1225 // ✅ Good - type-safe error handling
1226 if (error instanceof SchemaValidationError) {
1227 // Handle validation error
1228 }
1230 // ❌ Avoid - brittle string matching
1231 if (error.message.includes("validation failed")) {
1232 // Handle validation error
1233 }
1234 ```
1235
12362. **Import specific error types** - Import only the error classes you need for better tree-shaking
12373. **Always handle SchemaValidationError** - Provide clear feedback for validation failures
12384. **Check both questions** - Use `status` (`isLoading`, `isLoadingError`, `isCrashed`) for whether data can be shown, and `isSyncError` or `health` for whether it may be stale
12395. **Handle transaction promises** - Always handle `when('settled')` rejections
1240
1241## Example: Complete Error Handling
1242
1243```tsx
1244import {
1245 createCollection,
1246 createLiveQueryCollection,
1247 SchemaValidationError,
1248 DuplicateKeyError,
1249 UpdateKeyNotFoundError,
1250 DeleteKeyNotFoundError,
1251 TransactionNotPendingCommitError,
1252 createTransaction
1253} from "@tanstack/db"
1254import { useLiveQuery } from "@tanstack/react-db"
1255
1256const todoCollection = createCollection({
1257 id: "todos",
1258 schema: todoSchema,
1259 getKey: (todo) => todo.id,
1260 onInsert: async ({ transaction }) => {
1261 const response = await fetch("/api/todos", {
1262 method: "POST",
1263 body: JSON.stringify(transaction.mutations[0].modified),
1264 })
1265
1266 if (!response.ok) {
1267 throw new Error(`HTTP ${response.status}: ${response.statusText}`)
1268 }
1269
1270 },
1271 sync: {
1272 sync: ({ begin, write, commit, markReady }) => {
1273 // Your sync implementation
1274 begin()
1275 // ... sync logic
1276 commit()
1277 markReady()
1278 }
1279 }
1280})
1281
1282const todosQuery = createLiveQueryCollection((query) =>
1283 query.from({ todos: todoCollection })
1284)
1285
1286const TodoApp = () => {
1287 const { data, isLoadingError, isCrashed, isLoading, isSyncError } =
1288 useLiveQuery(todosQuery)
1289
1290 const handleAddTodo = async (text: string) => {
1291 try {
1292 const tx = await todoCollection.insert({
1293 id: crypto.randomUUID(),
1294 text,
1295 completed: false,
1296 })
1298 // Wait for persistence
1299 await tx.when('settled')
1300 } catch (error) {
1301 if (error instanceof SchemaValidationError) {
1302 alert(`Validation error: ${error.issues[0]?.message}`)
1303 } else if (error instanceof DuplicateKeyError) {
1304 alert("A todo with this ID already exists")
1305 } else {
1306 alert(`Failed to add todo: ${String(error)}`)
1307 }
1308 }
1309 }
1310
1311 const handleReload = async () => {
1312 try {
1313 await todosQuery.reload()
1314 } catch (error) {
1315 alert(`Failed to reload todos: ${String(error)}`)
1316 }
1317 }
1318
1319 if (isCrashed) {
1320 return <div>Local storage failed. Reload the page.</div>
1321 }
1322
1323 if (isLoadingError) {
1324 return (
1325 <div>
1326 <div>Todos could not load</div>
1327 <button onClick={handleReload}>Try again</button>
1328 </div>
1329 )
1330 }
1331
1332 if (isLoading) {
1333 return <div>Loading todos...</div>
1334 }
1335
1336 return (
1337 <div>
1338 {isSyncError && <div>Todos may be out of date</div>}
1339 <button onClick={() => handleAddTodo("New todo")}>
1340 Add Todo
1341 </button>
1342 {data.map((todo) => (
1343 <div key={todo.id}>{todo.text}</div>
1344 ))}
1345 </div>
1346 )
1347}
1348```
1349
1350## See Also
1351
1352- [API Reference](../overview.md#api-reference) - Detailed API documentation
1353- [Mutations Guide](../overview.md#making-optimistic-mutations) - Learn about optimistic updates and rollbacks
1354- [TanStack Query Error Handling](https://tanstack.com/query/latest/docs/react/guides/error-handling) - Query-specific error handling