我有以下代码:
const getJSON = async function(url, errorMsg = 'Something went wrong') {
return fetch(url).then(response => {
if (!response.ok) throw new Error(`${errorMsg} (${response.status})`);
return response.json();
});
};
const outerFunc = async function() {
try {
let x = await getJSON();
} catch (err) {
console.log(err);
}
}
outerFunc();
我试图在控制台中运行代码并得到一个错误:VM60:2 Fetch API cannot load chrome://new-tab-page/undefined. URL scheme "chrome" is not supported.
我想了解包围** outerFunc **函数的try/catch块是否可以捕获将由调用的异步函数( asyncFunction )或 asyncFunction 引起的错误,应由他自己处理。我知道在Java中可以“传播”错误。 JS中正确的行为是什么?
最佳答案
通常,您希望在可以对错误做出一些有用的事情的时候捕获错误。通常,这不是调用API的关键点,而是调用栈中更远的地方。允许错误自然向上传播到可以合理处理的位置是一个好主意。
例如,在实际的应用程序中,如果有一个catch块仅由console.log
组成,则通常(并非总是)指示错误应该在其他地方捕获。发生错误时,通常会想通知用户有问题,因此以下模式非常常见:
getAPI()
.then(populateWithResults)
.catch((error) => {
const div = document.querySelector('.errors').appendChild(document.createElement('div'));
div.textContent = 'There was an unexpected error: ' + error.message;
});
getAPI
不会自己捕获,而只是允许调用者处理可能的错误-类似于getJSON
函数正在执行的操作。通常,您只想在一个位置捕获错误,但是有时您可能想在多个地方捕获它-例如,子组件可能想在遇到错误时做一些特别的事情,但是它也想要通知 call 者有问题。在这种情况下,重新抛出该错误可能类似于:
const makeSubComponent = () => {
const componentContainer = document.querySelector('.container');
const populateSubComponent = () => {
// ...
};
return getAPI()
.then(populateSubComponent)
.catch((error) => {
componentContainer.textContent = 'Something went wrong...'
throw error; // Inform the caller of makeSubComponent of the error
});
};
允许makeSubComponent
及其调用者处理可能的问题。
关于javascript - 异步函数try catch block 是否可以包装称为异步函数,这也可能引发错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65707238/