Dealing with localStorage errors

published 2013-08-30

Web storage is pretty straightforward, but several otherwise helpful tutorials I went through brushed over error handling:

“QUOTA_EXCEEDED_ERR” is the exception that will get thrown if you exceed your storage quota of 5 megabytes.
Due to browser specific quotas you would want to check for exceptions so you would change line 1 above to the following.
try {
  localStorage.setItem("name", "Hello World!"); //saves to the database, "key", "value"
} catch (e) {
  if (e == QUOTA_EXCEEDED_ERR) {
    alert('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
  }
}

Is QUOTA_EXCEEDED_ERR some kind of global constant?

Chrome Developer tools says: ReferenceError: QUOTA_EXCEEDED_ERR is not defined.

Google suggests it might actually be DOMException.QUOTA_EXCEEDED_ERR, and Chrome agrees - DOMException.QUOTA_EXCEEDED_ERR is 22.

Is there a certain attribute of the exception that we should be matching to error code 22?

Let’s take a look. To generate the QUOTA_EXCEEDED_ERR exception we’ll attempt to store a 12MB string, which should exceed the quota. Open your developer tools console and enter:

var exception;
var repeat = function(str, x) { return new Array(x+1).join(str); };
var too_big = repeat("x", 12*1024*1024/2); // each JS character is 2 bytes
localStorage.clear();
try {
  localStorage.setItem("test", too_big);
} catch (e) {
  exception = e;
}

Then inspect exception.

Trying that in a few browsers, we observe:

Chrome

Exception in Chrome

Firefox

Exception in Firefox

Safari

Exception in Safari

There is no single attribute that we can depend on across browsers to detect that the error is in fact a QUOTA_EXCEEDED_ERR.

We could check exception instanceof DOMException, but to test such code we would need to be able to produce a mock DOMException instance. A SitePoint reference notes:

In practise, what we find is that most browsers implement DOM exceptions as part of their native mechanism...
It’s not possible to produce them cleanly from normal JavaScript.

Although localStorage quota errors are known by names such as QuotaExceededError and QUOTA_EXCEEDED_ERR, the only way to write testable, non-browser specific code is to accept any exception thrown during a storage attempt as a quota error. To differentiate between quota and support/security errors, be sure to detect the availability of localStorage separately.