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