Course contentsShow
← Web Development
Lesson 777 of 2,98214. Browser StorageFree lesson

Error Handling and QuotaExceededError

Catching storage errors, handling quota exceeded exceptions, and implementing fallback strategies.

Error Handling and QuotaExceededError

What you'll learn: How to gracefully handle storage failures when localStorage or sessionStorage runs out of space.

Why Storage Can Fail

Just like a physical drawer can get too full to close, browser storage has size limits (typically 5–10MB per origin). When you try to setItem and exceed this quota, the browser throws a QuotaExceededError. This can also happen in private/incognito modes where storage is often more restricted.

Without error handling, your app will crash. With it, you can respond intelligently.

Catching Storage Errors

Wrap your storage operations in a try...catch block:

try {
  localStorage.setItem('user', JSON.stringify(userData));
} catch (error) {
  if (error.name === 'QuotaExceededError') {
    console.error('Storage quota exceeded!');
    // Handle the quota issue
  }
}

Implementing Fallback Strategies

When storage fails, you have options:

Clear old data:

try {
  localStorage.setItem('newItem', value);
} catch (error) {
  if (error.name === 'QuotaExceededError') {
    localStorage.removeItem('oldItem'); // Free up space
    localStorage.setItem('newItem', value); // Try again
  }
}

Use in-memory fallback:

let memoryStorage = {};

function safeSetItem(key, value) {
  try {
    localStorage.setItem(key, value);
  } catch (error) {
    if (error.name === 'QuotaExceededError') {
      memoryStorage[key] = value; // Store in memory instead
      console.warn('Using memory fallback');
    }
  }
}

Notify the user:

catch (error) {
  if (error.name === 'QuotaExceededError') {
    alert('Storage is full. Please clear some data.');
  }
}

Key Takeaway: Always wrap setItem calls in try-catch blocks to handle QuotaExceededError, and implement fallback strategies like clearing old data, using in-memory storage, or notifying users when storage limits are reached.