[英]Is there a way to wrap an await/async try/catch block to every function?
[英]Does async function try catch block can wrap a called async function that also may throw an error?
我有以下代碼:
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 無法加載 chrome://new-tab-page/undefined。 URL 方案“chrome”不受支持。
我想了解 **outerFunc ** function 周圍的try/catch塊是否可以捕獲來自調用的異步 function ( asyncFunction ) 的錯誤,或者asyncFunction應該自己處理它的錯誤。 我知道在 Java 中可以“傳播”錯誤。 JS 中的正確行為是什么?
通常,您希望在某個點捕獲錯誤,以便您可以對錯誤做出有用的響應。 通常,這不是調用 API 的點,而是調用堆棧更上層的某個地方。 允許錯誤自然向上傳播到可以合理處理的地方是一個好主意。
例如,在實際應用程序中,如果有一個僅由console.log
組成的 catch 塊,這通常(並非總是)表明應該在其他地方捕獲錯誤。 當出現錯誤時,人們通常會想通知用戶出現了問題,因此以下這種模式非常常見:
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
function 正在做的事情。
通常你只想要一個錯誤被捕獲的點,但偶爾你可能想要在多個地方捕獲它 - 例如,也許一個子組件想要在遇到錯誤時做一些特別的事情,但它也想要通知呼叫者有問題。 在這種情況下,重新拋出錯誤可能如下所示:
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
及其調用者處理可能出現的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.