Error Handling and Success Callbacks
What you'll learn: How to write reliable IndexedDB code by properly handling both successful operations and errors.
Why Error Handling Matters
IndexedDB operations are asynchronous, meaning they happen in the background. Unlike simple code that runs line-by-line, these operations can succeed or fail, and you need to prepare for both outcomes. Think of it like ordering food delivery: you need a plan for when it arrives successfully (answer the door, enjoy your meal) and when it doesn't (call support, get a refund).
The Two Essential Callbacks
Every IndexedDB request returns a request object with two critical event handlers:
onsuccess fires when the operation completes successfully. This is where you access your data or confirm your changes worked.
onerror fires when something goes wrong—maybe the database is locked, the user denied permission, or storage is full.
The Pattern in Practice
Here's the reliable pattern for any IndexedDB operation:
const request = objectStore.get(42);
request.onsuccess = function(event) {
const data = event.target.result;
console.log('Retrieved:', data);
// Use your data here
};
request.onerror = function(event) {
console.error('Failed to retrieve:', event.target.error);
// Show user-friendly message or retry
};
Always attach both handlers. Even if you think nothing will go wrong, browsers can run out of storage, permissions can change, or network issues can interfere.
Making Your Code Bulletproof
Without error handlers, failures happen silently and your app appears broken to users. With proper handlers, you can log problems, show helpful messages, retry operations, or gracefully degrade functionality.
Key Takeaway: Always attach both onsuccess and onerror handlers to every IndexedDB request—successful operations need event.target.result to access data, while errors need handling to keep your app reliable and user-friendly.