我正在 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以及异常驱动的方法。引用的答案将分享如何强制执行可能捕获的异常。如果运行速度较低,上面的代码可能允许您执行/绕过某些逻辑。
关于javascript - 在 AngularJS 中,当 localStorage 已满时,如何捕获 ngStorage 的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30792370/