I came across this interview question which asked me the question how do you handle errors when localStorage permission is denied.
I researched through docs and found that such an issue could arise if user has setup browser to deny use of storing data. This results in code throwing SecurityError
I tried to come up with a solution by wrapping localStorage methods viz. setItem() & getItem() into try{..} catch(e){...} blocks.
I was curious to know if a browser fails to give access to localStorage What other options do I have to store my data so that I can gracefully handle this scenario ?
function CheckStorageAllowance() {
let storage;
try {
storage = window["localStorage"];
let x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
} catch (e) {
return e instanceof window.DOMException && (e.code === 22 || e.code === 1014 || e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && (storage && storage.length !== 0);
}
}
let check = CheckStorageAllowance();
if (check) {
// allowed
console.log("Works");
} else {
if (!check) {
console.log("disabled");
// Disabled
} else {
// quota exceeded
console.log(check);
}
}
So essentially we check if we can set an item, remove it fast and return true, if not we determine what the exception was and as you may see there's few potential problems that can occur. Good luck.