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

error-handling.md

575 lines14.9 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## Query Collection Error Tracking
49​
50Query collections provide enhanced error tracking utilities through the `utils` object. These methods expose error state information and provide recovery mechanisms for failed queries:
51​
52```tsx
53import { createCollection } from "@tanstack/db"
54import { queryCollectionOptions } from "@tanstack/query-db-collection"
55import { useLiveQuery } from "@tanstack/react-db"
56​
57const syncedCollection = createCollection(
58 queryCollectionOptions({
59 queryClient,
60 queryKey: ['synced-data'],
61 queryFn: fetchData,
62 getKey: (item) => item.id,
63 })
65​
66// Component can check error state
67function DataList() {
68 const { data } = useLiveQuery((q) => q.from({ item: syncedCollection }))
69 const isError = syncedCollection.utils.isError()
70 const errorCount = syncedCollection.utils.errorCount()
72 return (
73 <>
74 {isError && errorCount > 3 && (
75 <Alert>
76 Unable to sync. Showing cached data.
77 <button onClick={() => syncedCollection.utils.clearError()}>
78 Retry
79 </button>
80 </Alert>
81 )}
82 {/* Render data */}
83 </>
84 )
86```
87​
88Error tracking methods:
89- **`lastError()`**: Returns the most recent error encountered by the query, or `undefined` if no errors have occurred:
90- **`isError()`**: Returns a boolean indicating whether the collection is currently in an error state:
91- **`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:
92- **`clearError()`**: Clears the error state and triggers a refetch of the query. This method resets both `lastError` and `errorCount`:
93​
94## Collection Status and Error States
95​
96Collections track their status and transition between states:
97​
98```tsx
99import { useLiveQuery } from "@tanstack/react-db"
100​
101const TodoList = () => {
102 const { data, status, isError, isLoading, isReady } = useLiveQuery(
103 (query) => query.from({ todos: todoCollection })
104 )
105​
106 if (isError) {
107 return <div>Collection is in error state</div>
108 }
109​
110 if (isLoading) {
111 return <div>Loading...</div>
112 }
113​
114 return <div>{data?.map(todo => <div key={todo.id}>{todo.text}</div>)}</div>
116```
117​
118Collection status values:
119- `idle` - Not yet started
120- `loading` - Loading initial data
121- `initialCommit` - Processing initial data
122- `ready` - Ready for use
123- `error` - In error state
124- `cleaned-up` - Cleaned up and no longer usable
125​
126## Transaction Error Handling
127​
128When mutations fail, TanStack DB automatically rolls back optimistic updates:
129​
130```ts
131const todoCollection = createCollection({
132 id: "todos",
133 onInsert: async ({ transaction }) => {
134 const response = await fetch("/api/todos", {
135 method: "POST",
136 body: JSON.stringify(transaction.mutations[0].modified),
137 })
139 if (!response.ok) {
140 // Throwing an error will rollback the optimistic state
141 throw new Error(`HTTP Error: ${response.status}`)
142 }
144 return response.json()
145 },
146})
147​
148// Usage - optimistic update will be rolled back if the mutation fails
149try {
150 const tx = todoCollection.insert({
151 id: "1",
152 text: "New todo",
153 completed: false,
154 })
156 await tx.isPersisted.promise
157} catch (error) {
158 // The optimistic update has been automatically rolled back
159 console.error("Failed to create todo:", error)
161```
162​
163### Transaction States and Error Information
164​
165Transactions have the following states:
166- `pending` - Transaction is being processed
167- `persisting` - Currently executing the mutation function
168- `completed` - Transaction completed successfully
169- `failed` - Transaction failed and was rolled back
170​
171Access transaction error information from collection operations:
172​
173```ts
174const todoCollection = createCollection({
175 id: "todos",
176 onUpdate: async ({ transaction }) => {
177 const response = await fetch(`/api/todos/${transaction.mutations[0].key}`, {
178 method: "PUT",
179 body: JSON.stringify(transaction.mutations[0].modified),
180 })
182 if (!response.ok) {
183 throw new Error(`Update failed: ${response.status}`)
184 }
185 },
186})
187​
188try {
189 const tx = await todoCollection.update("todo-1", (draft) => {
190 draft.completed = true
191 })
193 await tx.isPersisted.promise
194} catch (error) {
195 // Transaction has been rolled back
196 console.log(tx.state) // "failed"
197 console.log(tx.error) // { message: "Update failed: 500", error: Error }
199```
200​
201Or with manual transaction creation:
202​
203```ts
204const tx = createTransaction({
205 mutationFn: async ({ transaction }) => {
206 throw new Error("API failed")
207 }
208})
209​
210tx.mutate(() => {
211 collection.insert({ id: "1", text: "Item" })
212})
213​
214try {
215 await tx.commit()
216} catch (error) {
217 // Transaction has been rolled back
218 console.log(tx.state) // "failed"
219 console.log(tx.error) // { message: "API failed", error: Error }
221```
222​
223## Collection Operation Errors
224​
225### Invalid Collection State
226​
227Collections in an `error` state cannot perform operations and must be manually recovered:
228​
229```ts
230import { CollectionInErrorStateError } from "@tanstack/db"
231​
232try {
233 todoCollection.insert(newTodo)
234} catch (error) {
235 if (error instanceof CollectionInErrorStateError) {
236 // Collection needs to be cleaned up and restarted
237 await todoCollection.cleanup()
239 // Now retry the operation
240 todoCollection.insert(newTodo)
241 }
243```
244​
245### Missing Mutation Handlers
246​
247Direct mutations require handlers to be configured:
248​
249```ts
250const todoCollection = createCollection({
251 id: "todos",
252 getKey: (todo) => todo.id,
253 // Missing onInsert handler
254})
255​
256// This will throw an error
257todoCollection.insert(newTodo)
258// Error: Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured
259```
260​
261### Duplicate Key Errors
262​
263Inserting items with existing keys will throw:
264​
265```ts
266import { DuplicateKeyError } from "@tanstack/db"
267​
268try {
269 todoCollection.insert({ id: "existing-id", text: "Todo" })
270} catch (error) {
271 if (error instanceof DuplicateKeyError) {
272 console.log(`Duplicate key: ${error.message}`)
273 }
275```
276​
277### Schema Validation Errors
278​
279Schema validation must be synchronous:
280​
281```ts
282const todoCollection = createCollection({
283 id: "todos",
284 getKey: (todo) => todo.id,
285 schema: {
286 "~standard": {
287 validate: async (data) => { // Async validation not allowed
288 // ...
289 }
290 }
291 }
292})
293​
294// Will throw: Schema validation must be synchronous
295```
296​
297## Sync Error Handling
298​
299### Query Collection Sync Errors
300​
301Query collections handle sync errors gracefully and mark the collection as ready even on error to avoid blocking applications:
302​
303```ts
304import { queryCollectionOptions } from "@tanstack/query-db-collection"
305​
306const todoCollection = createCollection(
307 queryCollectionOptions({
308 queryKey: ["todos"],
309 queryFn: async () => {
310 const response = await fetch("/api/todos")
311 if (!response.ok) {
312 throw new Error(`Failed to fetch: ${response.status}`)
313 }
314 return response.json()
315 },
316 queryClient,
317 getKey: (item) => item.id,
318 schema: todoSchema,
319 // Standard TanStack Query error handling options
320 retry: 3,
321 retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
322 })
324```
325​
326When sync errors occur:
327- Error is logged to console: `[QueryCollection] Error observing query...`
328- Collection is marked as ready to prevent blocking the application
329- Cached data remains available
330- Error tracking counters are updated (`lastError`, `errorCount`)
331​
332### Sync Write Errors
333​
334Sync functions must handle their own errors during write operations:
335​
336```ts
337const collection = createCollection({
338 id: "todos",
339 sync: {
340 sync: ({ begin, write, commit }) => {
341 begin()
343 try {
344 // Will throw if key already exists
345 write({ type: "insert", value: { id: "existing-id", text: "Todo" } })
346 } catch (error) {
347 // Error: Cannot insert document with key "existing-id" from sync because it already exists
348 }
350 commit()
351 }
352 }
353})
354```
355​
356### Cleanup Error Handling
357​
358Cleanup errors are isolated to prevent blocking the cleanup process:
359​
360```ts
361const collection = createCollection({
362 id: "todos",
363 sync: {
364 sync: ({ begin, commit }) => {
365 begin()
366 commit()
368 // Return a cleanup function
369 return () => {
370 // If this throws, the error is re-thrown in a microtask
371 // but cleanup continues successfully
372 throw new Error("Sync cleanup failed")
373 }
374 },
375 },
376})
377​
378// Cleanup completes even if the sync cleanup function throws
379await collection.cleanup() // Resolves successfully
380// Error is re-thrown asynchronously via queueMicrotask
381```
382​
383## Error Recovery Patterns
384​
385### Collection Cleanup and Restart
386​
387Clean up collections in error states:
388​
389```ts
390if (todoCollection.status === "error") {
391 // Cleanup will stop sync and reset the collection
392 await todoCollection.cleanup()
394 // Collection will automatically restart on next access
395 todoCollection.preload() // Or any other operation
397```
398​
399### Graceful Degradation
400​
401Collections continue to work with cached data even when sync fails:
402​
403```tsx
404const TodoApp = () => {
405 const { data, isError } = useLiveQuery((query) =>
406 query.from({ todos: todoCollection })
407 )
408​
409 return (
410 <div>
411 {isError && (
412 <div>Sync failed, but you can still view cached data</div>
413 )}
414 {data?.map(todo => <TodoItem key={todo.id} todo={todo} />)}
415 </div>
416 )
418```
419​
420### Transaction Rollback Cascading
421​
422When a transaction fails, conflicting transactions are automatically rolled back:
423​
424```ts
425const tx1 = createTransaction({ mutationFn: async () => {} })
426const tx2 = createTransaction({ mutationFn: async () => {} })
427​
428tx1.mutate(() => collection.update("1", draft => { draft.value = "A" }))
429tx2.mutate(() => collection.update("1", draft => { draft.value = "B" })) // Same item
430​
431// Rolling back tx1 will also rollback tx2 due to conflict
432tx1.rollback() // tx2 is automatically rolled back
433```
434​
435### Handling Invalid State Errors
436​
437Transactions validate their state before operations:
438​
439```ts
440const tx = createTransaction({ mutationFn: async () => {} })
441​
442// Complete the transaction
443await tx.commit()
444​
445// These will throw:
446tx.mutate(() => {}) // Error: You can no longer call .mutate() as the transaction is no longer pending
447tx.commit() // Error: You can no longer call .commit() as the transaction is no longer pending
448tx.rollback() // Error: You can no longer call .rollback() as the transaction is already completed
449```
450​
451## Best Practices
452​
4531. **Use instanceof checks** - Use `instanceof` instead of string matching for error handling:
454 ```ts
455 // ✅ Good - type-safe error handling
456 if (error instanceof SchemaValidationError) {
457 // Handle validation error
458 }
460 // ❌ Avoid - brittle string matching
461 if (error.message.includes("validation failed")) {
462 // Handle validation error
463 }
464 ```
465​
4662. **Import specific error types** - Import only the error classes you need for better tree-shaking
4673. **Always handle SchemaValidationError** - Provide clear feedback for validation failures
4684. **Check collection status** - Use `isError`, `isLoading`, `isReady` flags in React components
4695. **Handle transaction promises** - Always handle `isPersisted.promise` rejections
470​
471## Example: Complete Error Handling
472​
473```tsx
474import {
475 createCollection,
476 SchemaValidationError,
477 DuplicateKeyError,
478 createTransaction
479} from "@tanstack/db"
480import { useLiveQuery } from "@tanstack/react-db"
481​
482const todoCollection = createCollection({
483 id: "todos",
484 schema: todoSchema,
485 getKey: (todo) => todo.id,
486 onInsert: async ({ transaction }) => {
487 const response = await fetch("/api/todos", {
488 method: "POST",
489 body: JSON.stringify(transaction.mutations[0].modified),
490 })
491​
492 if (!response.ok) {
493 throw new Error(`HTTP ${response.status}: ${response.statusText}`)
494 }
495​
496 return response.json()
497 },
498 sync: {
499 sync: ({ begin, write, commit }) => {
500 // Your sync implementation
501 begin()
502 // ... sync logic
503 commit()
504 }
505 }
506})
507​
508const TodoApp = () => {
509 const { data, status, isError, isLoading } = useLiveQuery(
510 (query) => query.from({ todos: todoCollection })
511 )
512​
513 const handleAddTodo = async (text: string) => {
514 try {
515 const tx = await todoCollection.insert({
516 id: crypto.randomUUID(),
517 text,
518 completed: false,
519 })
521 // Wait for persistence
522 await tx.isPersisted.promise
523 } catch (error) {
524 if (error instanceof SchemaValidationError) {
525 alert(`Validation error: ${error.issues[0]?.message}`)
526 } else if (error instanceof DuplicateKeyError) {
527 alert("A todo with this ID already exists")
528 } else {
529 alert(`Failed to add todo: ${error.message}`)
530 }
531 }
532 }
533​
534 const handleCleanup = async () => {
535 try {
536 await todoCollection.cleanup()
537 // Collection will restart on next access
538 } catch (error) {
539 console.error("Cleanup failed:", error)
540 }
541 }
542​
543 if (isError) {
544 return (
545 <div>
546 <div>Collection error - data may be stale</div>
547 <button onClick={handleCleanup}>
548 Restart Collection
549 </button>
550 </div>
551 )
552 }
553​
554 if (isLoading) {
555 return <div>Loading todos...</div>
556 }
557​
558 return (
559 <div>
560 <button onClick={() => handleAddTodo("New todo")}>
561 Add Todo
562 </button>
563 {data?.map(todo => (
564 <div key={todo.id}>{todo.text}</div>
565 ))}
566 </div>
567 )
569```
570​
571## See Also
572​
573- [API Reference](../../overview.md#api-reference) - Detailed API documentation
574- [Mutations Guide](../../overview.md#making-optimistic-mutations) - Learn about optimistic updates and rollbacks
575- [TanStack Query Error Handling](https://tanstack.com/query/latest/docs/react/guides/error-handling) - Query-specific error handling