In angularjs how do you catch an error for ngStorage when localStorage is full?

299 views Asked by At

I am saving several items to localStorage using ngStorage in AngularJS, but if the user's localStorage is full how can I catch that error and allow the JavaScript to keep running?

try {  
    $scope.$storage.gridObject = $scope.gridConfig.data;  
    $scope.$storage.dataStored=true; 
}  
catch(err) {  
    //failed to save to local storage,  try clearing localStorage for IAP and throw error  
    $scope.$storage.dataStored=false;  
    $scope.$storage.$reset({    
        dataStored: false,
        gridObject: {}  
    })  
    console.log('error occured message');  
}
1

There are 1 answers

0
scniro On BEST ANSWER

Perhaps not specific to AngularJS, you should be able to get some detailed information for your localStorage with the following.

var allocated = 5; // default 5MB allocation
var total = 0;
for(var x in localStorage) {  
    var amount = (localStorage[x].length * 2) / 1024 / 1024;  
    total += amount;  
}
var remaining = allocated - total;
console.log( 'Used: ' + total + ' MB');
console.log( 'Remaining: ' + remaining + ' MB');

JSFiddle Link - demo

See this answer as well for an exception driven approach. The referenced answer will share how you can force an exception you can likely catch for. The code above may allow you to perform/bypass certain logic if you are running low.