1 回答

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超7個(gè)贊
在考慮 try/catch 塊時(shí),您走的是正確的道路,但請(qǐng)注意我也使用了“catch”。通常(也許這甚至是強(qiáng)制執(zhí)行的,我不記得了)你需要 catch 塊和 try。
所以你的函數(shù)看起來(lái)像這樣:
function async myFirstTryCatch() {
try {
// Make your request in the try block
await requestCall();
} catch(error){
// Hey, my http call returned an error
// Deal with the error here. Maybe show a toast, validate a form
// Anything you need to not break the code and have good UX
console.log(error)
}
}
按照同樣的思路,您可以讓每個(gè)函數(shù)處理自己的 try/catch,或者在您的應(yīng)用函數(shù)中控制它,以防某些鏈必須繼續(xù)/停止相互依賴(lài)。
function apply() {
try {
firstCall();
functionThatRequiresFirstCalltoSucceed();
} catch (error){
//Will catch if either firstCall or functionThatRequiresFirstCalltoSucceed fail
console.log(error)
}
functionThatIndependsFromTheResultAbove();
}
我希望這會(huì)幫助你建立關(guān)于 JS 錯(cuò)誤處理的想法 :)
重要說(shuō)明 如果您的代碼進(jìn)入 catch 塊,它將認(rèn)為錯(cuò)誤已被處理并且不會(huì)傳播!這是一個(gè)例子
function functionThatThrowsError(){
try{
throw new Error('Example Error!');
} catch (error) {
// Error has been dealt with
console.log(error) // Returns "Example Error"
// throw error; <--- Throw the error in the catch block if you need t to propagate
}
}
function wontCatchError() {
try {
functionThatThrowsError();
} catch (error) {
// THE CODE WILL NOT ENTER THE CATCH BLOCK
// SINCE THE ERROR WAS CAUGHT IN THE FUNCTION ITSELF.
// If you need to catch here as well, make sure to throw the error
// in the catch block of the 'functionThatThrowsError'
console.log(error)
}
}
添加回答
舉報(bào)