Even with Try{} Catch (e){} the script does not ignore the error -> Uncaught (in promise) SyntaxError: Unexpected end of Json Imput
Even with Try{} Catch (e){} the script does not ignore the error -> Uncaught (in promise) SyntaxError: Unexpected end of Json Imput
发生的事情是,在我的终端中我有一个 Python 实时更新 JSON 文件,导致文件打开有时更新数据,禁止 JavaScript无法访问,导致错误。
所以在这种情况下,我希望当 JavaScript 无法访问文件时,它不会传递错误,而是什么都不做,以继续显示错误之前收集的值.
但是正如我们在代码中看到的那样,我正在使用 try{}catch(e){}
,即使如此错误仍然出现
function refresh_images() {
try {
let selectedstages = document.getElementById("matches").selectedOptions[0].getAttribute("data-stages");
let selectedevents = document.getElementById("matches").selectedOptions[0].getAttribute("data-events");
fetch("testedropdown.json")
.then(response => response.json())
.then(data => {
console.log(data.Stages[selectedstages].Events[selectedevents].Eps)
})
} catch (e) {
}
}
fetch
执行异步操作,try/catch
只能捕获当第一个 运行 相应块内的代码时产生的错误(您的错误是在您的第一个 .then()
回调)。您可以添加一个 try/catch
包装 response.json()
,它会按您预期的那样工作。
或者,您可以安全地重新格式化您的代码,如下所示,利用承诺 catch
方法:
function refresh_images() {
const selectedstages = document.getElementById("matches").selectedOptions[0].getAttribute("data-stages");
const selectedevents = document.getElementById("matches").selectedOptions[0].getAttribute("data-events");
fetch("testedropdown.json")
.then(response => response.json())
.then(data => {
console.log(data.Stages[selectedstages].Events[selectedevents].Eps);
})
.catch((err) => {
console.log(err);
// HANDLE ERRORS HERE.
});
}
更多信息here。
发生的事情是,在我的终端中我有一个 Python 实时更新 JSON 文件,导致文件打开有时更新数据,禁止 JavaScript无法访问,导致错误。
所以在这种情况下,我希望当 JavaScript 无法访问文件时,它不会传递错误,而是什么都不做,以继续显示错误之前收集的值.
但是正如我们在代码中看到的那样,我正在使用 try{}catch(e){}
,即使如此错误仍然出现
function refresh_images() {
try {
let selectedstages = document.getElementById("matches").selectedOptions[0].getAttribute("data-stages");
let selectedevents = document.getElementById("matches").selectedOptions[0].getAttribute("data-events");
fetch("testedropdown.json")
.then(response => response.json())
.then(data => {
console.log(data.Stages[selectedstages].Events[selectedevents].Eps)
})
} catch (e) {
}
}
fetch
执行异步操作,try/catch
只能捕获当第一个 运行 相应块内的代码时产生的错误(您的错误是在您的第一个 .then()
回调)。您可以添加一个 try/catch
包装 response.json()
,它会按您预期的那样工作。
或者,您可以安全地重新格式化您的代码,如下所示,利用承诺 catch
方法:
function refresh_images() {
const selectedstages = document.getElementById("matches").selectedOptions[0].getAttribute("data-stages");
const selectedevents = document.getElementById("matches").selectedOptions[0].getAttribute("data-events");
fetch("testedropdown.json")
.then(response => response.json())
.then(data => {
console.log(data.Stages[selectedstages].Events[selectedevents].Eps);
})
.catch((err) => {
console.log(err);
// HANDLE ERRORS HERE.
});
}
更多信息here。