我有一个 try...catch
语句,它检查是否可以为对象的属性赋值,然后将其存储在本地存储中而不超出配额。
我在这里遇到的问题是,如果超出配额,它仍然为该属性分配了新值。
我不知道如何解决这个问题。我已经尝试过嵌套 try 语句并使用finally 语句,但我还没有弄清楚。
let storageFiles = JSON.parse(localStorage.getItem('storageFiles')) || {};
const image = document.getElementsByTagName('img')[0];
try {
// I need this block to only be executed if there's no error to catch
// but I will still need to assign the value to the property before
// saving it to local storage
storageFiles.source = image.src;
localStorage.setItem('storageFiles', JSON.stringify(storageFiles));
}
catch(err) {
console.log('Local storage error: ' + err);
}
本质上,我正在寻找一种方法,让我只在有错误或不会有错误的情况下才执行 try 语句中的代码。
我可以采取不同的方法吗?
最佳答案
Storage
interface 中没有任何内容它可以让您提前检查存储操作是否会成功。 JavaScript 中没有任何东西可以让您回滚代码的影响(例如回滚数据库事务)。您必须运行代码。
The issue I'm having here is that if it exceeds the quota, it still has assigned a new value to the property.
我猜您指的是您已解析的 storageFiles
对象的 source
属性。
我至少想到了两种解决方案:
您可以保留原始内容并在未保存时恢复更改:
let storageFiles = JSON.parse(localStorage.getItem('storageFiles')) || {}; const image = document.getElementsByTagName('img')[0]; const source = oldSource; try { storageFiles.source = image.src; localStorage.setItem('storageFiles', JSON.stringify(storageFiles)); } catch(err) { storageFiles.source = oldSource; console.log('Local storage error: ' + err); }
失败时重新解析对象:
let storageFiles = JSON.parse(localStorage.getItem('storageFiles')) || {}; const image = document.getElementsByTagName('img')[0]; try { storageFiles.source = image.src; localStorage.setItem('storageFiles', JSON.stringify(storageFiles)); } catch(err) { storageFiles = JSON.parse(localStorage.getItem('storageFiles')) || {}; console.log('Local storage error: ' + err); }
关于javascript - 仅在没有错误的情况下执行 try 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57574999/