Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

error-handling.md

1,352 lines45.4 KB

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 }
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 })
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 )
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)
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 )
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
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 ],
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 />
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 )
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 }
417​
419 health?.error && (
420 <button onClick={() => fetchNextPage()}>Retry loading more</button>
421 )
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 )
579​
580const App = () => (
581 <ErrorBoundary fallback={<div>Failed to load todos</div>}>
582 <Suspense fallback={<div>Loading...</div>}>
583 <TodoList />
584 </Suspense>
585 </ErrorBoundary>
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()
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​
665| Before | After |
666| --- | --- |
667| `isError` | `isLoadingError` (first load failed) or `isCrashed` (storage broke) |
668| `status: 'error'` after a crash | `status: 'crashed'` |
669| `markError(error)` | `fail(error)` |
670| `reportError(error, { final })` | `reportError(error)` or `fail(error)` |
671| node `phase`, `final`, `isError` | node `failureReason` or `error` |
672| node `instances` | removed |
673| `cleanup()` then `preload()` to recover | `reload()` |
674| `begin({ direct: true })` | `begin()`: every write applies on the kept rows |
675| a reload's first commit replaced every row | `begin({ snapshot: true })` or `truncate()` replaces them |
676| `markReady()` after `fail()` threw | it does nothing |
677| `cleanup()` with live queries mounted | rejects; unmount first or `cleanup({ dependents: true })` |
678| `persistedStatus`, `isPersistedReady`, `persistedError`, `preloadForInitialRender()` | `status` and `health` |
679| query-db `utils.lastError`, `isError`, `errorCount`, `clearError()` | `health`, `reload()` |
680​
681## Transaction Error Handling
682​
683When mutations fail, TanStack DB automatically rolls back optimistic updates:
684​
685```ts
686const todoCollection = createCollection({
687 id: "todos",
688 onInsert: async ({ transaction }) => {
689 const response = await fetch("/api/todos", {
690 method: "POST",
691 body: JSON.stringify(transaction.mutations[0].modified),
692 })
694 if (!response.ok) {
695 // Throwing an error will rollback the optimistic state
696 throw new Error(`HTTP Error: ${response.status}`)
697 }
699 return response.json()
700 },
701})
702​
703// Usage - optimistic update will be rolled back if the mutation fails
704try {
705 const tx = todoCollection.insert({
706 id: "1",
707 text: "New todo",
708 completed: false,
709 })
711 await tx.when('settled')
712} catch (error) {
713 // The optimistic update has been automatically rolled back
714 console.error("Failed to create todo:", error)
716```
717​
718### Transaction States and Error Information
719​
720Transactions have the following states:
721- `pending` - Transaction is being processed
722- `persisting` - Currently executing the mutation function
723- `completed` - Transaction completed successfully
724- `failed` - Transaction failed and was rolled back
725​
726Access transaction error information from collection operations:
727​
728```ts
729const todoCollection = createCollection({
730 id: "todos",
731 onUpdate: async ({ transaction }) => {
732 const response = await fetch(`/api/todos/${transaction.mutations[0].key}`, {
733 method: "PUT",
734 body: JSON.stringify(transaction.mutations[0].modified),
735 })
737 if (!response.ok) {
738 throw new Error(`Update failed: ${response.status}`)
739 }
740 },
741})
742​
743try {
744 const tx = await todoCollection.update("todo-1", (draft) => {
745 draft.completed = true
746 })
748 await tx.when('settled')
749} catch (error) {
750 // Transaction has been rolled back
751 console.log(tx.state) // "failed"
752 console.log(tx.error) // { message: "Update failed: 500", error: Error }
754```
755​
756Or with manual transaction creation:
757​
758```ts
759const tx = createTransaction({
760 mutationFn: async ({ transaction }) => {
761 throw new Error("API failed")
762 }
763})
764​
765tx.mutate(() => {
766 collection.insert({ id: "1", text: "Item" })
767})
768​
769try {
770 await tx.commit()
771} catch (error) {
772 // Transaction has been rolled back
773 console.log(tx.state) // "failed"
774 console.log(tx.error) // { message: "API failed", error: Error }
776```
777​
778Explicit cancellation is different from a mutation failure. If you call
779`tx.rollback()` while `mutationFn` is pending, the rollback settles
780`tx.when('settled')` as rejected. A later result or rejection from that
781mutation function is ignored: the outstanding `commit()` call resolves and
782`tx.error` is not populated by that late rejection. Observe `tx.when('settled')`
783when you need the transaction's outcome, including explicit cancellation.
784​
785After the mutation function succeeds, a publication listener can still throw
786while the completed transaction updates its collections. In that case
787`commit()` rejects with the listener error, but `tx.when('settled')` resolves
788and the transaction remains completed. This is not a persistence failure.
789​
790## Collection Operation Errors
791​
792### Invalid Collection State
793​
794A Collection whose first load failed (status `error`) or that crashed (status
795`crashed`) rejects writes with `CollectionInErrorStateError`. Recover by
796status:
797​
798- `error`: call `reload()`. It starts a new sync run, and live queries over the
799 Collection follow it. See [Reloading](#reloading).
800- `crashed`: a crash cannot be recovered in place, and `reload()` rejects.
801 Clean up the Collection together with everything that reads from it, then
802 start it again. Plain `cleanup()` rejects with `CollectionHasSubscribersError`
803 while a live query or an Effect reads the Collection. See
804 [When a Collection crashes](#when-a-collection-crashes).
805​
806```ts
807import { CollectionInErrorStateError } from "@tanstack/db"
808​
809try {
810 todoCollection.insert(newTodo)
811} catch (error) {
812 if (error instanceof CollectionInErrorStateError) {
813 if (todoCollection.status === "crashed") {
814 // Ends its live queries and Effects first; mount them again afterward.
815 await todoCollection.cleanup({ dependents: true })
816 await todoCollection.preload() // a fresh start
817 } else {
818 await todoCollection.reload() // the first load failed: try again
819 }
820​
821 // Now retry the operation
822 todoCollection.insert(newTodo)
823 }
825```
826​
827### Missing Mutation Handlers
828​
829Direct mutations require handlers to be configured:
830​
831```ts
832const todoCollection = createCollection({
833 id: "todos",
834 getKey: (todo) => todo.id,
835 // Missing onInsert handler
836})
837​
838// This will throw an error
839todoCollection.insert(newTodo)
840// Error: Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured
841```
842​
843### Insert Operation Errors
844​
845#### DuplicateKeyError
846​
847Thrown when inserting items with existing keys:
848​
849```ts
850import { DuplicateKeyError } from "@tanstack/db"
851​
852try {
853 todoCollection.insert({ id: "existing-id", text: "Todo" })
854} catch (error) {
855 if (error instanceof DuplicateKeyError) {
856 console.log(`Duplicate key: ${error.message}`)
857 // Consider using update() instead, or check if item exists first
858 }
860```
861​
862#### UndefinedKeyError
863​
864Thrown when an object is created without a defined key:
865​
866```ts
867import { UndefinedKeyError } from "@tanstack/db"
868​
869const collection = createCollection({
870 id: "todos",
871 getKey: (item) => item.id,
872})
873​
874try {
875 collection.insert({ text: "Todo" }) // Missing 'id' field
876} catch (error) {
877 if (error instanceof UndefinedKeyError) {
878 console.log("Item is missing required key field")
879 // Ensure your items have the key field defined by getKey
880 }
882```
883​
884### Update Operation Errors
885​
886#### UpdateKeyNotFoundError
887​
888Thrown when trying to update a key that doesn't exist in the collection:
889​
890```ts
891import { UpdateKeyNotFoundError } from "@tanstack/db"
892​
893try {
894 todoCollection.update("nonexistent-key", draft => {
895 draft.completed = true
896 })
897} catch (error) {
898 if (error instanceof UpdateKeyNotFoundError) {
899 console.log("Key not found - item may have been deleted")
900 // Consider using insert() if the item doesn't exist
901 }
903```
904​
905#### KeyUpdateNotAllowedError
906​
907Thrown when attempting to change an item's key (not allowed - delete and re-insert instead):
908​
909```ts
910import { KeyUpdateNotAllowedError } from "@tanstack/db"
911​
912try {
913 todoCollection.update("todo-1", draft => {
914 draft.id = "todo-2" // Not allowed!
915 })
916} catch (error) {
917 if (error instanceof KeyUpdateNotAllowedError) {
918 console.log("Cannot change item keys")
919 // Instead, delete the old item and insert a new one
920 }
922```
923​
924### Delete Operation Errors
925​
926#### DeleteKeyNotFoundError
927​
928Thrown when trying to delete a key that doesn't exist:
929​
930```ts
931import { DeleteKeyNotFoundError } from "@tanstack/db"
932​
933try {
934 todoCollection.delete("nonexistent-key")
935} catch (error) {
936 if (error instanceof DeleteKeyNotFoundError) {
937 console.log("Key not found - item may have already been deleted")
938 // This may be acceptable in some scenarios (idempotent deletes)
939 }
941```
942​
943## Sync Error Handling
944​
945### Query Collection Sync Errors
946​
947Query collections distinguish an initial load failure from a later refetch failure:
948​
949```ts
950import { queryCollectionOptions } from "@tanstack/query-db-collection"
951​
952const todoCollection = createCollection(
953 queryCollectionOptions({
954 queryKey: ["todos"],
955 queryFn: async () => {
956 const response = await fetch("/api/todos")
957 if (!response.ok) {
958 throw new Error(`Failed to fetch: ${response.status}`)
959 }
960 return response.json()
961 },
962 queryClient,
963 getKey: (item) => item.id,
964 schema: todoSchema,
965 // Standard TanStack Query error handling options
966 retry: 3,
967 retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
968 })
970```
971​
972When sync errors occur:
973- Error is logged to console: `[QueryCollection] Error observing query...`
974- 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
975- A later refetch failure keeps the Collection `ready` with its cached data and sets the source node's `failureReason`, because TanStack Query fetches again
976- A later successful refetch clears the `failureReason`
977- To retry a failed first load, call `collection.reload()`
978​
979### Sync Write Errors
980​
981Sync functions must handle their own errors during write operations:
982​
983```ts
984const collection = createCollection({
985 id: "todos",
986 sync: {
987 sync: ({ begin, write, commit }) => {
988 begin()
990 try {
991 // Will throw if key already exists
992 write({ type: "insert", value: { id: "existing-id", text: "Todo" } })
993 } catch (error) {
994 // Error: Cannot insert document with key "existing-id" from sync because it already exists
995 }
997 commit()
998 }
999 }
1001```
1002​
1003### Cleanup Error Handling
1004​
1005Cleanup errors are isolated to prevent blocking the cleanup process:
1006​
1007```ts
1008const collection = createCollection({
1009 id: "todos",
1010 sync: {
1011 sync: ({ begin, commit }) => {
1012 begin()
1013 commit()
1015 // Return a cleanup function
1016 return () => {
1017 // If this throws, the error is re-thrown in a microtask
1018 // but cleanup continues successfully
1019 throw new Error("Sync cleanup failed")
1021 },
1022 },
1024​
1025// Cleanup completes even if the sync cleanup function throws
1026await collection.cleanup() // Resolves successfully
1027// Error is re-thrown asynchronously via queueMicrotask
1028```
1029​
1030## Error Recovery Patterns
1031​
1032### Reload or Recreate
1033​
1034To retry a failed first load or a stopped sync, call `reload()` on the
1035Collection or on the live query that reads it. See [Reloading](#reloading). A
1036crashed Collection cannot reload; clean it up with `{ dependents: true }` and
1037start it again. See [When a Collection crashes](#when-a-collection-crashes).
1038​
1039### Graceful Degradation
1040​
1041After the first ready, Collections keep working with their rows when sync
1042fails. The health tree tells you which source has the problem and whether its
1043sync adapter is still trying:
1044​
1045```tsx
1046import { findProblems } from "@tanstack/db"
1047import { useLiveQuery } from "@tanstack/react-db"
1048​
1049const TodoApp = () => {
1050 const { data, health, collection } = useLiveQuery((query) =>
1051 query.from({ todos: todoCollection })
1053 const [problem] = health ? findProblems(health) : []
1054​
1055 return (
1056 <div>
1057 {problem?.error && (
1058 <div>
1059 Sync stopped.{" "}
1060 <button onClick={() => collection.reload()}>Reload</button>
1061 </div>
1062 )}
1063 {problem?.failureReason && <div>Reconnecting. Showing saved data.</div>}
1064 {data.map((todo) => <TodoItem key={todo.id} todo={todo} />)}
1065 </div>
1068```
1069​
1070### Transaction Rollback Cascading
1071​
1072When a transaction fails, conflicting transactions are automatically rolled back:
1073​
1074```ts
1075const tx1 = createTransaction({ mutationFn: async () => {} })
1076const tx2 = createTransaction({ mutationFn: async () => {} })
1077​
1078tx1.mutate(() => collection.update("1", draft => { draft.value = "A" }))
1079tx2.mutate(() => collection.update("1", draft => { draft.value = "B" })) // Same item
1080​
1081// Rolling back tx1 will also rollback tx2 due to conflict
1082tx1.rollback() // tx2 is automatically rolled back
1083```
1084​
1085### Transaction Lifecycle Errors
1086​
1087Transactions validate their state before operations to prevent misuse. Here are the specific errors you may encounter:
1088​
1089#### MissingMutationFunctionError
1090​
1091Thrown when creating a transaction without a required `mutationFn`:
1092​
1093```ts
1094import { MissingMutationFunctionError } from "@tanstack/db"
1095​
1096try {
1097 const tx = createTransaction({}) // Missing mutationFn
1098} catch (error) {
1099 if (error instanceof MissingMutationFunctionError) {
1100 console.log("mutationFn is required when creating a transaction")
1103```
1104​
1105#### TransactionNotPendingMutateError
1106​
1107Thrown when calling `mutate()` after a transaction is no longer pending:
1108​
1109```ts
1110import { TransactionNotPendingMutateError } from "@tanstack/db"
1111​
1112const tx = createTransaction({ mutationFn: async () => {} })
1113​
1114await tx.commit()
1115​
1116try {
1117 tx.mutate(() => {
1118 collection.insert({ id: "1", text: "Item" })
1119 })
1120} catch (error) {
1121 if (error instanceof TransactionNotPendingMutateError) {
1122 console.log("Cannot mutate - transaction is no longer pending")
1125```
1126​
1127#### TransactionNotPendingCommitError
1128​
1129Thrown when calling `commit()` after a transaction is no longer pending:
1130​
1131```ts
1132import { TransactionNotPendingCommitError } from "@tanstack/db"
1133​
1134const tx = createTransaction({ mutationFn: async () => {} })
1135tx.mutate(() => collection.insert({ id: "1", text: "Item" }))
1136​
1137await tx.commit()
1138​
1139try {
1140 await tx.commit() // Trying to commit again
1141} catch (error) {
1142 if (error instanceof TransactionNotPendingCommitError) {
1143 console.log("Transaction already committed")
1146```
1147​
1148#### TransactionAlreadyCompletedRollbackError
1149​
1150Thrown when calling `rollback()` on a transaction that's already completed:
1151​
1152```ts
1153import { TransactionAlreadyCompletedRollbackError } from "@tanstack/db"
1154​
1155const tx = createTransaction({ mutationFn: async () => {} })
1156tx.mutate(() => collection.insert({ id: "1", text: "Item" }))
1157​
1158await tx.commit()
1159​
1160try {
1161 tx.rollback() // Can't rollback after commit
1162} catch (error) {
1163 if (error instanceof TransactionAlreadyCompletedRollbackError) {
1164 console.log("Cannot rollback - transaction already completed")
1167```
1168​
1169### Sync Transaction Errors
1170​
1171When working with sync transactions, these errors can occur:
1172​
1173#### NoPendingSyncTransactionWriteError
1174​
1175Thrown when calling `write()` without an active sync transaction:
1176​
1177```ts
1178const collection = createCollection({
1179 id: "todos",
1180 sync: {
1181 sync: ({ write }) => {
1182 // Calling write without begin() first
1183 write({ type: "insert", value: { id: "1", text: "Todo" } })
1184 // Error: No pending sync transaction to write to
1188```
1189​
1190#### SyncTransactionAlreadyCommittedWriteError
1191​
1192Thrown when calling `write()` after the sync transaction is already committed:
1193​
1194```ts
1195const collection = createCollection({
1196 id: "todos",
1197 sync: {
1198 sync: ({ begin, write, commit }) => {
1199 begin()
1200 commit()
1201​
1202 // Trying to write after commit
1203 write({ type: "insert", value: { id: "1", text: "Todo" } })
1204 // Error: The pending sync transaction is already committed
1208```
1209​
1210#### NoPendingSyncTransactionCommitError
1211​
1212Thrown when calling `commit()` without an active sync transaction.
1213​
1214#### SyncTransactionAlreadyCommittedError
1215​
1216Thrown when calling `commit()` on a sync transaction that's already committed.
1217​
1218## Best Practices
1219​
12201. **Use instanceof checks** - Use `instanceof` instead of string matching for error handling:
1221 ```ts
1222 // ✅ Good - type-safe error handling
1223 if (error instanceof SchemaValidationError) {
1224 // Handle validation error
1227 // ❌ Avoid - brittle string matching
1228 if (error.message.includes("validation failed")) {
1229 // Handle validation error
1231 ```
1232​
12332. **Import specific error types** - Import only the error classes you need for better tree-shaking
12343. **Always handle SchemaValidationError** - Provide clear feedback for validation failures
12354. **Check both questions** - Use `status` (`isLoading`, `isLoadingError`, `isCrashed`) for whether data can be shown, and `isSyncError` or `health` for whether it may be stale
12365. **Handle transaction promises** - Always handle `when('settled')` rejections
1237​
1238## Example: Complete Error Handling
1239​
1240```tsx
1241import {
1242 createCollection,
1243 createLiveQueryCollection,
1244 SchemaValidationError,
1245 DuplicateKeyError,
1246 UpdateKeyNotFoundError,
1247 DeleteKeyNotFoundError,
1248 TransactionNotPendingCommitError,
1249 createTransaction
1250} from "@tanstack/db"
1251import { useLiveQuery } from "@tanstack/react-db"
1252​
1253const todoCollection = createCollection({
1254 id: "todos",
1255 schema: todoSchema,
1256 getKey: (todo) => todo.id,
1257 onInsert: async ({ transaction }) => {
1258 const response = await fetch("/api/todos", {
1259 method: "POST",
1260 body: JSON.stringify(transaction.mutations[0].modified),
1261 })
1262​
1263 if (!response.ok) {
1264 throw new Error(`HTTP ${response.status}: ${response.statusText}`)
1266​
1267 return response.json()
1268 },
1269 sync: {
1270 sync: ({ begin, write, commit, markReady }) => {
1271 // Your sync implementation
1272 begin()
1273 // ... sync logic
1274 commit()
1275 markReady()
1279​
1280const todosQuery = createLiveQueryCollection((query) =>
1281 query.from({ todos: todoCollection })
1283​
1284const TodoApp = () => {
1285 const { data, isLoadingError, isCrashed, isLoading, isSyncError } =
1286 useLiveQuery(todosQuery)
1287​
1288 const handleAddTodo = async (text: string) => {
1289 try {
1290 const tx = await todoCollection.insert({
1291 id: crypto.randomUUID(),
1292 text,
1293 completed: false,
1294 })
1296 // Wait for persistence
1297 await tx.when('settled')
1298 } catch (error) {
1299 if (error instanceof SchemaValidationError) {
1300 alert(`Validation error: ${error.issues[0]?.message}`)
1301 } else if (error instanceof DuplicateKeyError) {
1302 alert("A todo with this ID already exists")
1303 } else {
1304 alert(`Failed to add todo: ${String(error)}`)
1308​
1309 const handleReload = async () => {
1310 try {
1311 await todosQuery.reload()
1312 } catch (error) {
1313 alert(`Failed to reload todos: ${String(error)}`)
1316​
1317 if (isCrashed) {
1318 return <div>Local storage failed. Reload the page.</div>
1320​
1321 if (isLoadingError) {
1322 return (
1323 <div>
1324 <div>Todos could not load</div>
1325 <button onClick={handleReload}>Try again</button>
1326 </div>
1329​
1330 if (isLoading) {
1331 return <div>Loading todos...</div>
1333​
1334 return (
1335 <div>
1336 {isSyncError && <div>Todos may be out of date</div>}
1337 <button onClick={() => handleAddTodo("New todo")}>
1338 Add Todo
1339 </button>
1340 {data.map((todo) => (
1341 <div key={todo.id}>{todo.text}</div>
1342 ))}
1343 </div>
1346```
1347​
1348## See Also
1349​
1350- [API Reference](../overview.md#api-reference) - Detailed API documentation
1351- [Mutations Guide](../overview.md#making-optimistic-mutations) - Learn about optimistic updates and rollbacks
1352- [TanStack Query Error Handling](https://tanstack.com/query/latest/docs/react/guides/error-handling) - Query-specific error handling