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

error-handling.md

815 lines21.1 KB

1---
2title: Error Handling
3id: error-handling
4---
5​
6# Error Handling
7​
8TanStack 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.
9​
10## Error Types
11​
12TanStack 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`):
13​
14```ts
15import {
16 SchemaValidationError,
17 CollectionInErrorStateError,
18 DuplicateKeyError,
19 MissingHandlerError,
20 TransactionError,
21 // ... and many more
22} from "@tanstack/db"
23```
24​
25### SchemaValidationError
26​
27Thrown when data doesn't match the collection's schema during insert or update operations:
28​
29```ts
30import { SchemaValidationError } from "@tanstack/db"
31​
32try {
33 todoCollection.insert({ text: 123 }) // Invalid type
34} catch (error) {
35 if (error instanceof SchemaValidationError) {
36 console.log(error.type) // 'insert' or 'update'
37 console.log(error.issues) // Array of validation issues
38 // Example issue: { message: "Expected string, received number", path: ["text"] }
39 }
41```
42​
43The error includes:
44- `type`: Whether it was an 'insert' or 'update' operation
45- `issues`: Array of validation issues with messages and paths
46- `message`: A formatted error message listing all issues
47​
48**When schema validation occurs:**
49​
50Schema validation happens only for **client mutations** - when you explicitly insert or update data:
51​
521. **During inserts** - When `collection.insert()` is called
532. **During updates** - When `collection.update()` is called
54​
55Schemas do **not** validate data coming from your server or sync layer. That data is assumed to already be valid.
56​
57```typescript
58const schema = z.object({
59 id: z.string(),
60 created_at: z.string().transform(val => new Date(val))
61 // TInput: string, TOutput: Date
62})
63​
64// Validation happens here ✓
65collection.insert({
66 id: "1",
67 created_at: "2024-01-01" // TInput: string
68})
69// If successful, stores: { created_at: Date } // TOutput: Date
70```
71​
72For more details on schema validation and type transformations, see the [Schemas guide](./schemas.md).
73​
74## Query Collection Error Tracking
75​
76Query collections provide enhanced error tracking utilities through the `utils` object. These methods expose error state information and provide recovery mechanisms for failed queries:
77​
78```tsx
79import { createCollection } from "@tanstack/db"
80import { queryCollectionOptions } from "@tanstack/query-db-collection"
81import { useLiveQuery } from "@tanstack/react-db"
82​
83const syncedCollection = createCollection(
84 queryCollectionOptions({
85 queryClient,
86 queryKey: ['synced-data'],
87 queryFn: fetchData,
88 getKey: (item) => item.id,
89 })
91​
92// Component can check error state
93function DataList() {
94 const { data } = useLiveQuery((q) => q.from({ item: syncedCollection }))
95 const isError = syncedCollection.utils.isError
96 const errorCount = syncedCollection.utils.errorCount
98 return (
99 <>
100 {isError && errorCount > 3 && (
101 <Alert>
102 Unable to sync. Showing cached data.
103 <button onClick={() => syncedCollection.utils.clearError()}>
104 Retry
105 </button>
106 </Alert>
107 )}
108 {/* Render data */}
109 </>
110 )
112```
113​
114Error tracking methods:
115- **`lastError`**: Returns the most recent error encountered by the query, or `undefined` if no errors have occurred:
116- **`isError`**: Returns a boolean indicating whether the collection is currently in an error state:
117- **`errorCount`**: Returns the number of consecutive sync failures. This counter is incremented only when queries fail completely (not per retry attempt) and is reset on successful queries:
118- **`clearError()`**: Clears the error state and triggers a refetch of the query. This method resets both `lastError` and `errorCount`:
119​
120## Collection Status and Error States
121​
122Collections track their status and transition between states:
123​
124```tsx
125import { useLiveQuery } from "@tanstack/react-db"
126​
127const TodoList = () => {
128 const { data, status, isError, isLoading, isReady } = useLiveQuery(
129 (query) => query.from({ todos: todoCollection })
130 )
131​
132 if (isError) {
133 return <div>Collection is in error state</div>
134 }
135​
136 if (isLoading) {
137 return <div>Loading...</div>
138 }
139​
140 return <div>{data?.map(todo => <div key={todo.id}>{todo.text}</div>)}</div>
142```
143​
144Collection status values:
145- `idle` - Not yet started
146- `loading` - Loading initial data
147- `initialCommit` - Processing initial data
148- `ready` - Ready for use
149- `error` - In error state
150- `cleaned-up` - Cleaned up and no longer usable
151​
152### Using Suspense and Error Boundaries (React)
153​
154For React applications, you can handle loading and error states with `useLiveSuspenseQuery`, React Suspense, and Error Boundaries:
155​
156```tsx
157import { useLiveSuspenseQuery } from "@tanstack/react-db"
158import { Suspense } from "react"
159import { ErrorBoundary } from "react-error-boundary"
160​
161const TodoList = () => {
162 // No need to check status - Suspense and ErrorBoundary handle it
163 const { data } = useLiveSuspenseQuery(
164 (query) => query.from({ todos: todoCollection })
165 )
166​
167 // data is always defined here
168 return <div>{data.map(todo => <div key={todo.id}>{todo.text}</div>)}</div>
170​
171const App = () => (
172 <ErrorBoundary fallback={<div>Failed to load todos</div>}>
173 <Suspense fallback={<div>Loading...</div>}>
174 <TodoList />
175 </Suspense>
176 </ErrorBoundary>
178```
179​
180With this approach, loading states are handled by `<Suspense>` and error states are handled by `<ErrorBoundary>` instead of within your component logic. See the [React Suspense section in Live Queries](./live-queries#using-with-react-suspense) for more details.
181​
182## Transaction Error Handling
183​
184When mutations fail, TanStack DB automatically rolls back optimistic updates:
185​
186```ts
187const todoCollection = createCollection({
188 id: "todos",
189 onInsert: async ({ transaction }) => {
190 const response = await fetch("/api/todos", {
191 method: "POST",
192 body: JSON.stringify(transaction.mutations[0].modified),
193 })
195 if (!response.ok) {
196 // Throwing an error will rollback the optimistic state
197 throw new Error(`HTTP Error: ${response.status}`)
198 }
200 return response.json()
201 },
202})
203​
204// Usage - optimistic update will be rolled back if the mutation fails
205try {
206 const tx = todoCollection.insert({
207 id: "1",
208 text: "New todo",
209 completed: false,
210 })
212 await tx.isPersisted.promise
213} catch (error) {
214 // The optimistic update has been automatically rolled back
215 console.error("Failed to create todo:", error)
217```
218​
219### Transaction States and Error Information
220​
221Transactions have the following states:
222- `pending` - Transaction is being processed
223- `persisting` - Currently executing the mutation function
224- `completed` - Transaction completed successfully
225- `failed` - Transaction failed and was rolled back
226​
227Access transaction error information from collection operations:
228​
229```ts
230const todoCollection = createCollection({
231 id: "todos",
232 onUpdate: async ({ transaction }) => {
233 const response = await fetch(`/api/todos/${transaction.mutations[0].key}`, {
234 method: "PUT",
235 body: JSON.stringify(transaction.mutations[0].modified),
236 })
238 if (!response.ok) {
239 throw new Error(`Update failed: ${response.status}`)
240 }
241 },
242})
243​
244try {
245 const tx = await todoCollection.update("todo-1", (draft) => {
246 draft.completed = true
247 })
249 await tx.isPersisted.promise
250} catch (error) {
251 // Transaction has been rolled back
252 console.log(tx.state) // "failed"
253 console.log(tx.error) // { message: "Update failed: 500", error: Error }
255```
256​
257Or with manual transaction creation:
258​
259```ts
260const tx = createTransaction({
261 mutationFn: async ({ transaction }) => {
262 throw new Error("API failed")
263 }
264})
265​
266tx.mutate(() => {
267 collection.insert({ id: "1", text: "Item" })
268})
269​
270try {
271 await tx.commit()
272} catch (error) {
273 // Transaction has been rolled back
274 console.log(tx.state) // "failed"
275 console.log(tx.error) // { message: "API failed", error: Error }
277```
278​
279## Collection Operation Errors
280​
281### Invalid Collection State
282​
283Collections in an `error` state cannot perform operations and must be manually recovered:
284​
285```ts
286import { CollectionInErrorStateError } from "@tanstack/db"
287​
288try {
289 todoCollection.insert(newTodo)
290} catch (error) {
291 if (error instanceof CollectionInErrorStateError) {
292 // Collection needs to be cleaned up and restarted
293 await todoCollection.cleanup()
295 // Now retry the operation
296 todoCollection.insert(newTodo)
297 }
299```
300​
301### Missing Mutation Handlers
302​
303Direct mutations require handlers to be configured:
304​
305```ts
306const todoCollection = createCollection({
307 id: "todos",
308 getKey: (todo) => todo.id,
309 // Missing onInsert handler
310})
311​
312// This will throw an error
313todoCollection.insert(newTodo)
314// Error: Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured
315```
316​
317### Insert Operation Errors
318​
319#### DuplicateKeyError
320​
321Thrown when inserting items with existing keys:
322​
323```ts
324import { DuplicateKeyError } from "@tanstack/db"
325​
326try {
327 todoCollection.insert({ id: "existing-id", text: "Todo" })
328} catch (error) {
329 if (error instanceof DuplicateKeyError) {
330 console.log(`Duplicate key: ${error.message}`)
331 // Consider using update() instead, or check if item exists first
332 }
334```
335​
336#### UndefinedKeyError
337​
338Thrown when an object is created without a defined key:
339​
340```ts
341import { UndefinedKeyError } from "@tanstack/db"
342​
343const collection = createCollection({
344 id: "todos",
345 getKey: (item) => item.id,
346})
347​
348try {
349 collection.insert({ text: "Todo" }) // Missing 'id' field
350} catch (error) {
351 if (error instanceof UndefinedKeyError) {
352 console.log("Item is missing required key field")
353 // Ensure your items have the key field defined by getKey
354 }
356```
357​
358### Update Operation Errors
359​
360#### UpdateKeyNotFoundError
361​
362Thrown when trying to update a key that doesn't exist in the collection:
363​
364```ts
365import { UpdateKeyNotFoundError } from "@tanstack/db"
366​
367try {
368 todoCollection.update("nonexistent-key", draft => {
369 draft.completed = true
370 })
371} catch (error) {
372 if (error instanceof UpdateKeyNotFoundError) {
373 console.log("Key not found - item may have been deleted")
374 // Consider using insert() if the item doesn't exist
375 }
377```
378​
379#### KeyUpdateNotAllowedError
380​
381Thrown when attempting to change an item's key (not allowed - delete and re-insert instead):
382​
383```ts
384import { KeyUpdateNotAllowedError } from "@tanstack/db"
385​
386try {
387 todoCollection.update("todo-1", draft => {
388 draft.id = "todo-2" // Not allowed!
389 })
390} catch (error) {
391 if (error instanceof KeyUpdateNotAllowedError) {
392 console.log("Cannot change item keys")
393 // Instead, delete the old item and insert a new one
394 }
396```
397​
398### Delete Operation Errors
399​
400#### DeleteKeyNotFoundError
401​
402Thrown when trying to delete a key that doesn't exist:
403​
404```ts
405import { DeleteKeyNotFoundError } from "@tanstack/db"
406​
407try {
408 todoCollection.delete("nonexistent-key")
409} catch (error) {
410 if (error instanceof DeleteKeyNotFoundError) {
411 console.log("Key not found - item may have already been deleted")
412 // This may be acceptable in some scenarios (idempotent deletes)
413 }
415```
416​
417## Sync Error Handling
418​
419### Query Collection Sync Errors
420​
421Query collections handle sync errors gracefully and mark the collection as ready even on error to avoid blocking applications:
422​
423```ts
424import { queryCollectionOptions } from "@tanstack/query-db-collection"
425​
426const todoCollection = createCollection(
427 queryCollectionOptions({
428 queryKey: ["todos"],
429 queryFn: async () => {
430 const response = await fetch("/api/todos")
431 if (!response.ok) {
432 throw new Error(`Failed to fetch: ${response.status}`)
433 }
434 return response.json()
435 },
436 queryClient,
437 getKey: (item) => item.id,
438 schema: todoSchema,
439 // Standard TanStack Query error handling options
440 retry: 3,
441 retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
442 })
444```
445​
446When sync errors occur:
447- Error is logged to console: `[QueryCollection] Error observing query...`
448- Collection is marked as ready to prevent blocking the application
449- Cached data remains available
450- Error tracking counters are updated (`lastError`, `errorCount`)
451​
452### Sync Write Errors
453​
454Sync functions must handle their own errors during write operations:
455​
456```ts
457const collection = createCollection({
458 id: "todos",
459 sync: {
460 sync: ({ begin, write, commit }) => {
461 begin()
463 try {
464 // Will throw if key already exists
465 write({ type: "insert", value: { id: "existing-id", text: "Todo" } })
466 } catch (error) {
467 // Error: Cannot insert document with key "existing-id" from sync because it already exists
468 }
470 commit()
471 }
472 }
473})
474```
475​
476### Cleanup Error Handling
477​
478Cleanup errors are isolated to prevent blocking the cleanup process:
479​
480```ts
481const collection = createCollection({
482 id: "todos",
483 sync: {
484 sync: ({ begin, commit }) => {
485 begin()
486 commit()
488 // Return a cleanup function
489 return () => {
490 // If this throws, the error is re-thrown in a microtask
491 // but cleanup continues successfully
492 throw new Error("Sync cleanup failed")
493 }
494 },
495 },
496})
497​
498// Cleanup completes even if the sync cleanup function throws
499await collection.cleanup() // Resolves successfully
500// Error is re-thrown asynchronously via queueMicrotask
501```
502​
503## Error Recovery Patterns
504​
505### Collection Cleanup and Restart
506​
507Clean up collections in error states:
508​
509```ts
510if (todoCollection.status === "error") {
511 // Cleanup will stop sync and reset the collection
512 await todoCollection.cleanup()
514 // Collection will automatically restart on next access
515 todoCollection.preload() // Or any other operation
517```
518​
519### Graceful Degradation
520​
521Collections continue to work with cached data even when sync fails:
522​
523```tsx
524const TodoApp = () => {
525 const { data, isError } = useLiveQuery((query) =>
526 query.from({ todos: todoCollection })
527 )
528​
529 return (
530 <div>
531 {isError && (
532 <div>Sync failed, but you can still view cached data</div>
533 )}
534 {data?.map(todo => <TodoItem key={todo.id} todo={todo} />)}
535 </div>
536 )
538```
539​
540### Transaction Rollback Cascading
541​
542When a transaction fails, conflicting transactions are automatically rolled back:
543​
544```ts
545const tx1 = createTransaction({ mutationFn: async () => {} })
546const tx2 = createTransaction({ mutationFn: async () => {} })
547​
548tx1.mutate(() => collection.update("1", draft => { draft.value = "A" }))
549tx2.mutate(() => collection.update("1", draft => { draft.value = "B" })) // Same item
550​
551// Rolling back tx1 will also rollback tx2 due to conflict
552tx1.rollback() // tx2 is automatically rolled back
553```
554​
555### Transaction Lifecycle Errors
556​
557Transactions validate their state before operations to prevent misuse. Here are the specific errors you may encounter:
558​
559#### MissingMutationFunctionError
560​
561Thrown when creating a transaction without a required `mutationFn`:
562​
563```ts
564import { MissingMutationFunctionError } from "@tanstack/db"
565​
566try {
567 const tx = createTransaction({}) // Missing mutationFn
568} catch (error) {
569 if (error instanceof MissingMutationFunctionError) {
570 console.log("mutationFn is required when creating a transaction")
571 }
573```
574​
575#### TransactionNotPendingMutateError
576​
577Thrown when calling `mutate()` after a transaction is no longer pending:
578​
579```ts
580import { TransactionNotPendingMutateError } from "@tanstack/db"
581​
582const tx = createTransaction({ mutationFn: async () => {} })
583​
584await tx.commit()
585​
586try {
587 tx.mutate(() => {
588 collection.insert({ id: "1", text: "Item" })
589 })
590} catch (error) {
591 if (error instanceof TransactionNotPendingMutateError) {
592 console.log("Cannot mutate - transaction is no longer pending")
593 }
595```
596​
597#### TransactionNotPendingCommitError
598​
599Thrown when calling `commit()` after a transaction is no longer pending:
600​
601```ts
602import { TransactionNotPendingCommitError } from "@tanstack/db"
603​
604const tx = createTransaction({ mutationFn: async () => {} })
605tx.mutate(() => collection.insert({ id: "1", text: "Item" }))
606​
607await tx.commit()
608​
609try {
610 await tx.commit() // Trying to commit again
611} catch (error) {
612 if (error instanceof TransactionNotPendingCommitError) {
613 console.log("Transaction already committed")
614 }
616```
617​
618#### TransactionAlreadyCompletedRollbackError
619​
620Thrown when calling `rollback()` on a transaction that's already completed:
621​
622```ts
623import { TransactionAlreadyCompletedRollbackError } from "@tanstack/db"
624​
625const tx = createTransaction({ mutationFn: async () => {} })
626tx.mutate(() => collection.insert({ id: "1", text: "Item" }))
627​
628await tx.commit()
629​
630try {
631 tx.rollback() // Can't rollback after commit
632} catch (error) {
633 if (error instanceof TransactionAlreadyCompletedRollbackError) {
634 console.log("Cannot rollback - transaction already completed")
635 }
637```
638​
639### Sync Transaction Errors
640​
641When working with sync transactions, these errors can occur:
642​
643#### NoPendingSyncTransactionWriteError
644​
645Thrown when calling `write()` without an active sync transaction:
646​
647```ts
648const collection = createCollection({
649 id: "todos",
650 sync: {
651 sync: ({ write }) => {
652 // Calling write without begin() first
653 write({ type: "insert", value: { id: "1", text: "Todo" } })
654 // Error: No pending sync transaction to write to
655 }
656 }
657})
658```
659​
660#### SyncTransactionAlreadyCommittedWriteError
661​
662Thrown when calling `write()` after the sync transaction is already committed:
663​
664```ts
665const collection = createCollection({
666 id: "todos",
667 sync: {
668 sync: ({ begin, write, commit }) => {
669 begin()
670 commit()
671​
672 // Trying to write after commit
673 write({ type: "insert", value: { id: "1", text: "Todo" } })
674 // Error: The pending sync transaction is already committed
675 }
676 }
677})
678```
679​
680#### NoPendingSyncTransactionCommitError
681​
682Thrown when calling `commit()` without an active sync transaction.
683​
684#### SyncTransactionAlreadyCommittedError
685​
686Thrown when calling `commit()` on a sync transaction that's already committed.
687​
688## Best Practices
689​
6901. **Use instanceof checks** - Use `instanceof` instead of string matching for error handling:
691 ```ts
692 // ✅ Good - type-safe error handling
693 if (error instanceof SchemaValidationError) {
694 // Handle validation error
695 }
697 // ❌ Avoid - brittle string matching
698 if (error.message.includes("validation failed")) {
699 // Handle validation error
700 }
701 ```
702​
7032. **Import specific error types** - Import only the error classes you need for better tree-shaking
7043. **Always handle SchemaValidationError** - Provide clear feedback for validation failures
7054. **Check collection status** - Use `isError`, `isLoading`, `isReady` flags in React components
7065. **Handle transaction promises** - Always handle `isPersisted.promise` rejections
707​
708## Example: Complete Error Handling
709​
710```tsx
711import {
712 createCollection,
713 SchemaValidationError,
714 DuplicateKeyError,
715 UpdateKeyNotFoundError,
716 DeleteKeyNotFoundError,
717 TransactionNotPendingCommitError,
718 createTransaction
719} from "@tanstack/db"
720import { useLiveQuery } from "@tanstack/react-db"
721​
722const todoCollection = createCollection({
723 id: "todos",
724 schema: todoSchema,
725 getKey: (todo) => todo.id,
726 onInsert: async ({ transaction }) => {
727 const response = await fetch("/api/todos", {
728 method: "POST",
729 body: JSON.stringify(transaction.mutations[0].modified),
730 })
731​
732 if (!response.ok) {
733 throw new Error(`HTTP ${response.status}: ${response.statusText}`)
734 }
735​
736 return response.json()
737 },
738 sync: {
739 sync: ({ begin, write, commit }) => {
740 // Your sync implementation
741 begin()
742 // ... sync logic
743 commit()
744 }
745 }
746})
747​
748const TodoApp = () => {
749 const { data, status, isError, isLoading } = useLiveQuery(
750 (query) => query.from({ todos: todoCollection })
751 )
752​
753 const handleAddTodo = async (text: string) => {
754 try {
755 const tx = await todoCollection.insert({
756 id: crypto.randomUUID(),
757 text,
758 completed: false,
759 })
761 // Wait for persistence
762 await tx.isPersisted.promise
763 } catch (error) {
764 if (error instanceof SchemaValidationError) {
765 alert(`Validation error: ${error.issues[0]?.message}`)
766 } else if (error instanceof DuplicateKeyError) {
767 alert("A todo with this ID already exists")
768 } else {
769 alert(`Failed to add todo: ${error.message}`)
770 }
771 }
772 }
773​
774 const handleCleanup = async () => {
775 try {
776 await todoCollection.cleanup()
777 // Collection will restart on next access
778 } catch (error) {
779 console.error("Cleanup failed:", error)
780 }
781 }
782​
783 if (isError) {
784 return (
785 <div>
786 <div>Collection error - data may be stale</div>
787 <button onClick={handleCleanup}>
788 Restart Collection
789 </button>
790 </div>
791 )
792 }
793​
794 if (isLoading) {
795 return <div>Loading todos...</div>
796 }
797​
798 return (
799 <div>
800 <button onClick={() => handleAddTodo("New todo")}>
801 Add Todo
802 </button>
803 {data?.map(todo => (
804 <div key={todo.id}>{todo.text}</div>
805 ))}
806 </div>
807 )
809```
810​
811## See Also
812​
813- [API Reference](../overview.md#api-reference) - Detailed API documentation
814- [Mutations Guide](../overview.md#making-optimistic-mutations) - Learn about optimistic updates and rollbacks
815- [TanStack Query Error Handling](https://tanstack.com/query/latest/docs/react/guides/error-handling) - Query-specific error handling