2015-06-11 35 views
1

我在AngularJS中使用ngStoragelocalStorage中保存了幾個項目,但如果用戶的localStorage已滿,我如何捕獲該錯誤並允許JavaScript繼續運行?在angularjs中,當localStorage已滿時,你如何捕獲ngStorage的錯誤?

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'); 
} 

回答

0

也許不是特定於AngularJS,你應該能夠得到一些詳細的資料爲您localStorage有以下幾點。

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 - 演示

this answer以及一個例外驅動的方法。引用的答案將分享如何強制你可能會遇到的異常。上面的代碼可能允許您在低電平時執行/跳過某些邏輯。

相關問題