Dev.to WebDev 🛠 Dev 👁 0 📖 3 min read

Handling localStorage Errors with try...catch

localStorage is simple to use, but it is not guaranteed to work every time. A browser can block access to it, or the available storage space can run out. Without proper handling, a storage error may stop part of the appl

localStorage is simple to use, but it is not guaranteed to work every time. A browser can block access to it, or the available storage space can run out. Without proper handling, a storage error may stop part of the application. As developers, we should anticipate these situations and provide a safe alternative, so users can continue using the main features without interruptions.

1. The problem: localStorage can become unavailable

We often use localStorage as if it were always accessible:

localStorage.setItem("theme", "dark");

This usually works without problems. However, browser settings, security policies and storage limits may cause the operation to throw an exception.

The Web Storage API is synchronous, so the exception occurs immediately. If it is not handled, the current JavaScript function stops running.

2. The main errors

Two errors are particularly important.

A SecurityError may appear when the browser prevents the page from accessing storage. The cause can be the page origin, a browser setting or a privacy policy.

A QuotaExceededError is thrown when setItem() cannot store more data because the available space has been reached.

These situations are uncommon in a small application, but they are still possible.

3. Handling read errors with try...catch

When an application starts, it may try to retrieve a previously saved value. If that value cannot be accessed, the application still needs an initial value.

function getSavedDraft() {
  try {
    return localStorage.getItem("draft") || "";
  } catch (error) {
    console.error("Unable to read the saved draft:", error);
    return "";
  }
}

The empty string acts as a fallback. It does not solve the storage problem, but it allows the application to start with an empty draft instead of stopping.

4. Handling write and removal errors

Saving and removing data happen at different moments, so each operation should be handled separately.

try {
  localStorage.setItem("draft", currentDraft);
} catch (error) {
  console.error("Unable to save the draft:", error);
}

When the browser rejects the write operation, the user can still continue editing the current draft in memory.

The same approach can be used when clearing saved data:

try {
  localStorage.removeItem("draft");
} catch (error) {
  console.error("Failed to clear the saved draft:", error);
}

A storage problem should not prevent the interface from updating.

5. Choosing the fallback behaviour

The best alternative depends on the operation.

If the application cannot read the saved data, it can use an empty string or another safe default. If it cannot save a new value, it should keep the current data in memory so the user does not lose their work. If it cannot remove an old value, it can still clear the interface and report the error. The old value may remain in storage.

The main feature should continue working even when storage is unavailable.

6. The same principle applies to sessionStorage

sessionStorage uses the same Web Storage API and can produce similar errors. The main difference is its lifetime: localStorage persists between browser sessions, while sessionStorage lasts only for the current browser tab.

Its getItem(), setItem() and removeItem() operations should therefore be handled in the same way.

7. Conclusion

try...catch does not guarantee that browser storage will always be available. It gives the application a controlled response when storage cannot be used.

By handling reads, writes and removals separately, we can choose a suitable fallback for each operation and keep the application usable when persistence is unavailable.

Tip: Separate try...catch blocks work well when an application has only a few storage operations. If localStorage is used in many places, a shared storage utility can manage operations, errors and fallback values in one place.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.