gpt4 book ai didi

javascript - 只有在没有错误的情况下才执行 try 语句

转载 作者:行者123 更新时间:2023-11-29 10:26:37 25 4
gpt4 key购买 nike

我有一个 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 属性。

至少想到了两种解决方案:

  1. 您可以保留原始文件并在未保存时还原更改:

    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);
    }
  2. 失败时重新解析对象:

    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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com