在 angularjs 中,当 localStorage 已满时如何捕获 ngStorage 的错误?
In angularjs how do you catch an error for ngStorage when localStorage is full?
我正在使用 AngularJS 中的 ngStorage
将几项保存到 localStorage
,但是如果用户的 localStorage
已满,我如何捕获该错误并允许 JavaScript 保持 运行?
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');
}
也许不特定于 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 以了解异常驱动方法。引用的答案将分享如何强制执行可能捕获的异常。如果您 运行 低,上面的代码可能允许您 perform/bypass 某些逻辑。
我正在使用 AngularJS 中的 ngStorage
将几项保存到 localStorage
,但是如果用户的 localStorage
已满,我如何捕获该错误并允许 JavaScript 保持 运行?
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');
}
也许不特定于 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 以了解异常驱动方法。引用的答案将分享如何强制执行可能捕获的异常。如果您 运行 低,上面的代码可能允许您 perform/bypass 某些逻辑。